<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>django.db.models.query &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../../../index.html" />
    <link rel="up" title="django.db.models" href="../models.html" />



 
<script type="text/javascript" src="../../../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../../../index.html">Home</a>  |
        <a title="Table of contents" href="../../../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../../../genindex.html">Index</a>  |
        <a title="Module index" href="../../../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    <a href="../../../index.html" title="Module code" accesskey="U">up</a></div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="_modules-django-db-models-query">
            
  <h1>Source code for django.db.models.query</h1><div class="highlight"><pre>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">The main QuerySet implementation. This provides the public API for the ORM.</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="kn">import</span> <span class="nn">copy</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">exceptions</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connections</span><span class="p">,</span> <span class="n">router</span><span class="p">,</span> <span class="n">transaction</span><span class="p">,</span> <span class="n">IntegrityError</span>
<span class="kn">from</span> <span class="nn">django.db.models.constants</span> <span class="kn">import</span> <span class="n">LOOKUP_SEP</span>
<span class="kn">from</span> <span class="nn">django.db.models.fields</span> <span class="kn">import</span> <span class="n">AutoField</span><span class="p">,</span> <span class="n">Empty</span>
<span class="kn">from</span> <span class="nn">django.db.models.query_utils</span> <span class="kn">import</span> <span class="p">(</span><span class="n">Q</span><span class="p">,</span> <span class="n">select_related_descend</span><span class="p">,</span>
    <span class="n">deferred_class_factory</span><span class="p">,</span> <span class="n">InvalidQuery</span><span class="p">)</span>
<span class="kn">from</span> <span class="nn">django.db.models.deletion</span> <span class="kn">import</span> <span class="n">Collector</span>
<span class="kn">from</span> <span class="nn">django.db.models.sql.constants</span> <span class="kn">import</span> <span class="n">CURSOR</span>
<span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">sql</span>
<span class="kn">from</span> <span class="nn">django.utils.functional</span> <span class="kn">import</span> <span class="n">partition</span>
<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">six</span>
<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>

<span class="c"># The maximum number (one less than the max to be precise) of results to fetch</span>
<span class="c"># in a get() query</span>
<span class="n">MAX_GET_RESULTS</span> <span class="o">=</span> <span class="mi">20</span>

<span class="c"># The maximum number of items to display in a QuerySet.__repr__</span>
<span class="n">REPR_OUTPUT_SIZE</span> <span class="o">=</span> <span class="mi">20</span>

<span class="c"># Pull into this namespace for backwards compatibility.</span>
<span class="n">EmptyResultSet</span> <span class="o">=</span> <span class="n">sql</span><span class="o">.</span><span class="n">EmptyResultSet</span>


<span class="k">def</span> <span class="nf">_pickle_queryset</span><span class="p">(</span><span class="n">class_bases</span><span class="p">,</span> <span class="n">class_dict</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Used by `__reduce__` to create the initial version of the `QuerySet` class</span>
<span class="sd">    onto which the output of `__getstate__` will be applied.</span>

<span class="sd">    See `__reduce__` for more details.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">new</span> <span class="o">=</span> <span class="n">Empty</span><span class="p">()</span>
    <span class="n">new</span><span class="o">.</span><span class="n">__class__</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">class_bases</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">class_bases</span><span class="p">,</span> <span class="n">class_dict</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">new</span>


<div class="viewcode-block" id="QuerySet"><a class="viewcode-back" href="../../../../ref/models/querysets.html#django.db.models.query.QuerySet">[docs]</a><span class="k">class</span> <span class="nc">QuerySet</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Represents a lazy database lookup for a set of objects.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">query</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">hints</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">model</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_db</span> <span class="o">=</span> <span class="n">using</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_hints</span> <span class="o">=</span> <span class="n">hints</span> <span class="ow">or</span> <span class="p">{}</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="n">query</span> <span class="ow">or</span> <span class="n">sql</span><span class="o">.</span><span class="n">Query</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_sticky_filter</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_done</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_known_related_objects</span> <span class="o">=</span> <span class="p">{}</span>        <span class="c"># {rel_field, {pk: rel_obj}}</span>

    <span class="k">def</span> <span class="nf">as_manager</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span>
        <span class="c"># Address the circular dependency between `Queryset` and `Manager`.</span>
        <span class="kn">from</span> <span class="nn">django.db.models.manager</span> <span class="kn">import</span> <span class="n">Manager</span>
        <span class="k">return</span> <span class="n">Manager</span><span class="o">.</span><span class="n">from_queryset</span><span class="p">(</span><span class="n">cls</span><span class="p">)()</span>
    <span class="n">as_manager</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="n">as_manager</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">as_manager</span><span class="p">)</span>

    <span class="c">########################</span>
    <span class="c"># PYTHON MAGIC METHODS #</span>
    <span class="c">########################</span>

    <span class="k">def</span> <span class="nf">__deepcopy__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">memo</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Deep copy of a QuerySet doesn&#39;t populate the cache</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="p">()</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">__dict__</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">k</span> <span class="o">==</span> <span class="s">&#39;_result_cache&#39;</span><span class="p">:</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">__dict__</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">__dict__</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">copy</span><span class="o">.</span><span class="n">deepcopy</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">memo</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">__getstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Allows the QuerySet to be pickled.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c"># Force the cache to be fully populated.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_fetch_all</span><span class="p">()</span>
        <span class="n">obj_dict</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__dict__</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">obj_dict</span>

    <span class="k">def</span> <span class="nf">__reduce__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Used by pickle to deal with the types that we create dynamically when</span>
<span class="sd">        specialized queryset such as `ValuesQuerySet` are used in conjunction</span>
<span class="sd">        with querysets that are *subclasses* of `QuerySet`.</span>

<span class="sd">        See `_clone` implementation for more details.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&#39;_specialized_queryset_class&#39;</span><span class="p">):</span>
            <span class="n">class_bases</span> <span class="o">=</span> <span class="p">(</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_specialized_queryset_class</span><span class="p">,</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_base_queryset_class</span><span class="p">,</span>
            <span class="p">)</span>
            <span class="n">class_dict</span> <span class="o">=</span> <span class="p">{</span>
                <span class="s">&#39;_specialized_queryset_class&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_specialized_queryset_class</span><span class="p">,</span>
                <span class="s">&#39;_base_queryset_class&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_base_queryset_class</span><span class="p">,</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="n">_pickle_queryset</span><span class="p">,</span> <span class="p">(</span><span class="n">class_bases</span><span class="p">,</span> <span class="n">class_dict</span><span class="p">),</span> <span class="bp">self</span><span class="o">.</span><span class="n">__getstate__</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">QuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__reduce__</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">data</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="p">[:</span><span class="n">REPR_OUTPUT_SIZE</span> <span class="o">+</span> <span class="mi">1</span><span class="p">])</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="o">&gt;</span> <span class="n">REPR_OUTPUT_SIZE</span><span class="p">:</span>
            <span class="n">data</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="s">&quot;...(remaining elements truncated)...&quot;</span>
        <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_fetch_all</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        The queryset iterator protocol uses three nested iterators in the</span>
<span class="sd">        default case:</span>
<span class="sd">            1. sql.compiler:execute_sql()</span>
<span class="sd">               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)</span>
<span class="sd">                 using cursor.fetchmany(). This part is responsible for</span>
<span class="sd">                 doing some column masking, and returning the rows in chunks.</span>
<span class="sd">            2. sql/compiler.results_iter()</span>
<span class="sd">               - Returns one row at time. At this point the rows are still just</span>
<span class="sd">                 tuples. In some cases the return values are converted to</span>
<span class="sd">                 Python values at this location (see resolve_columns(),</span>
<span class="sd">                 resolve_aggregate()).</span>
<span class="sd">            3. self.iterator()</span>
<span class="sd">               - Responsible for turning the rows into model objects.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_fetch_all</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__nonzero__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_fetch_all</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">bool</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Retrieves an item or slice from the set of results.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">(</span><span class="nb">slice</span><span class="p">,)</span> <span class="o">+</span> <span class="n">six</span><span class="o">.</span><span class="n">integer_types</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">TypeError</span>
        <span class="k">assert</span> <span class="p">((</span><span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">slice</span><span class="p">)</span> <span class="ow">and</span> <span class="p">(</span><span class="n">k</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">))</span> <span class="ow">or</span>
                <span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">slice</span><span class="p">)</span> <span class="ow">and</span> <span class="p">(</span><span class="n">k</span><span class="o">.</span><span class="n">start</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">k</span><span class="o">.</span><span class="n">start</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="ow">and</span>
                 <span class="p">(</span><span class="n">k</span><span class="o">.</span><span class="n">stop</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">k</span><span class="o">.</span><span class="n">stop</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">))),</span> \
            <span class="s">&quot;Negative indexing is not supported.&quot;</span>

        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">[</span><span class="n">k</span><span class="p">]</span>

        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">slice</span><span class="p">):</span>
            <span class="n">qs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
            <span class="k">if</span> <span class="n">k</span><span class="o">.</span><span class="n">start</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="n">start</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">k</span><span class="o">.</span><span class="n">start</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">start</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="k">if</span> <span class="n">k</span><span class="o">.</span><span class="n">stop</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="n">stop</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">k</span><span class="o">.</span><span class="n">stop</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">stop</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="n">qs</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_limits</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">stop</span><span class="p">)</span>
            <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="n">qs</span><span class="p">)[::</span><span class="n">k</span><span class="o">.</span><span class="n">step</span><span class="p">]</span> <span class="k">if</span> <span class="n">k</span><span class="o">.</span><span class="n">step</span> <span class="k">else</span> <span class="n">qs</span>

        <span class="n">qs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">qs</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_limits</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">k</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="n">qs</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">__and__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_merge_sanity_check</span><span class="p">(</span><span class="n">other</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">EmptyQuerySet</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">other</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">EmptyQuerySet</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span>
        <span class="n">combined</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">combined</span><span class="o">.</span><span class="n">_merge_known_related_objects</span><span class="p">(</span><span class="n">other</span><span class="p">)</span>
        <span class="n">combined</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">combine</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">query</span><span class="p">,</span> <span class="n">sql</span><span class="o">.</span><span class="n">AND</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">combined</span>

    <span class="k">def</span> <span class="nf">__or__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_merge_sanity_check</span><span class="p">(</span><span class="n">other</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">EmptyQuerySet</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">other</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">EmptyQuerySet</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span>
        <span class="n">combined</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">combined</span><span class="o">.</span><span class="n">_merge_known_related_objects</span><span class="p">(</span><span class="n">other</span><span class="p">)</span>
        <span class="n">combined</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">combine</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">query</span><span class="p">,</span> <span class="n">sql</span><span class="o">.</span><span class="n">OR</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">combined</span>

    <span class="c">####################################</span>
    <span class="c"># METHODS THAT DO DATABASE QUERIES #</span>
    <span class="c">####################################</span>

    <span class="k">def</span> <span class="nf">iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        An iterator over the results from applying this QuerySet to the</span>
<span class="sd">        database.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">fill_cache</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="k">if</span> <span class="n">connections</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">]</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">supports_select_related</span><span class="p">:</span>
            <span class="n">fill_cache</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_related</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">fill_cache</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
            <span class="n">requested</span> <span class="o">=</span> <span class="n">fill_cache</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">requested</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="n">max_depth</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">max_depth</span>

        <span class="n">extra_select</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">extra_select</span><span class="p">)</span>
        <span class="n">aggregate_select</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">aggregate_select</span><span class="p">)</span>

        <span class="n">only_load</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_loaded_field_names</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">fill_cache</span><span class="p">:</span>
            <span class="n">fields</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span>

        <span class="n">load_fields</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="c"># If only/defer clauses have been specified,</span>
        <span class="c"># build the list of fields that are to be loaded.</span>
        <span class="k">if</span> <span class="n">only_load</span><span class="p">:</span>
            <span class="k">for</span> <span class="n">field</span><span class="p">,</span> <span class="n">model</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_concrete_fields_with_model</span><span class="p">():</span>
                <span class="k">if</span> <span class="n">model</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
                    <span class="n">model</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span>
                <span class="k">try</span><span class="p">:</span>
                    <span class="k">if</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span> <span class="ow">in</span> <span class="n">only_load</span><span class="p">[</span><span class="n">model</span><span class="p">]:</span>
                        <span class="c"># Add a field that has been explicitly included</span>
                        <span class="n">load_fields</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
                <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
                    <span class="c"># Model wasn&#39;t explicitly listed in the only_load table</span>
                    <span class="c"># Therefore, we need to load all fields from this model</span>
                    <span class="n">load_fields</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>

        <span class="n">index_start</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">extra_select</span><span class="p">)</span>
        <span class="n">aggregate_start</span> <span class="o">=</span> <span class="n">index_start</span> <span class="o">+</span> <span class="nb">len</span><span class="p">(</span><span class="n">load_fields</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">)</span>

        <span class="n">skip</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="k">if</span> <span class="n">load_fields</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">fill_cache</span><span class="p">:</span>
            <span class="c"># Some fields have been deferred, so we have to initialize</span>
            <span class="c"># via keyword arguments.</span>
            <span class="n">skip</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
            <span class="n">init_list</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">load_fields</span><span class="p">:</span>
                    <span class="n">skip</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">init_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
            <span class="n">model_cls</span> <span class="o">=</span> <span class="n">deferred_class_factory</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">skip</span><span class="p">)</span>

        <span class="c"># Cache db and model outside the loop</span>
        <span class="n">db</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>
        <span class="n">model</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span>
        <span class="n">compiler</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="n">db</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">fill_cache</span><span class="p">:</span>
            <span class="n">klass_info</span> <span class="o">=</span> <span class="n">get_klass_info</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">max_depth</span><span class="o">=</span><span class="n">max_depth</span><span class="p">,</span>
                                        <span class="n">requested</span><span class="o">=</span><span class="n">requested</span><span class="p">,</span> <span class="n">only_load</span><span class="o">=</span><span class="n">only_load</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">compiler</span><span class="o">.</span><span class="n">results_iter</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">fill_cache</span><span class="p">:</span>
                <span class="n">obj</span><span class="p">,</span> <span class="n">_</span> <span class="o">=</span> <span class="n">get_cached_row</span><span class="p">(</span><span class="n">row</span><span class="p">,</span> <span class="n">index_start</span><span class="p">,</span> <span class="n">db</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">,</span>
                                        <span class="n">offset</span><span class="o">=</span><span class="nb">len</span><span class="p">(</span><span class="n">aggregate_select</span><span class="p">))</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c"># Omit aggregates in object creation.</span>
                <span class="n">row_data</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="n">index_start</span><span class="p">:</span><span class="n">aggregate_start</span><span class="p">]</span>
                <span class="k">if</span> <span class="n">skip</span><span class="p">:</span>
                    <span class="n">obj</span> <span class="o">=</span> <span class="n">model_cls</span><span class="p">(</span><span class="o">**</span><span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">init_list</span><span class="p">,</span> <span class="n">row_data</span><span class="p">)))</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">obj</span> <span class="o">=</span> <span class="n">model</span><span class="p">(</span><span class="o">*</span><span class="n">row_data</span><span class="p">)</span>

                <span class="c"># Store the source database of the object</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">db</span> <span class="o">=</span> <span class="n">db</span>
                <span class="c"># This object came from the database; it&#39;s not being added.</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="bp">False</span>

            <span class="k">if</span> <span class="n">extra_select</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">extra_select</span><span class="p">):</span>
                    <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>

            <span class="c"># Add the aggregates to the model</span>
            <span class="k">if</span> <span class="n">aggregate_select</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">aggregate</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">aggregate_select</span><span class="p">):</span>
                    <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">aggregate</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="n">aggregate_start</span><span class="p">])</span>

            <span class="c"># Add the known related objects to the model, if there are any</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_known_related_objects</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">field</span><span class="p">,</span> <span class="n">rel_objs</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_known_related_objects</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
                    <span class="c"># Avoid overwriting objects loaded e.g. by select_related</span>
                    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">()):</span>
                        <span class="k">continue</span>
                    <span class="n">pk</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">get_attname</span><span class="p">())</span>
                    <span class="k">try</span><span class="p">:</span>
                        <span class="n">rel_obj</span> <span class="o">=</span> <span class="n">rel_objs</span><span class="p">[</span><span class="n">pk</span><span class="p">]</span>
                    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
                        <span class="k">pass</span>               <span class="c"># may happen in qs1 | qs2 scenarios</span>
                    <span class="k">else</span><span class="p">:</span>
                        <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">rel_obj</span><span class="p">)</span>

            <span class="k">yield</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">aggregate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a dictionary containing the calculations (aggregation)</span>
<span class="sd">        over the current queryset</span>

<span class="sd">        If args is present the expression is passed as a kwarg using</span>
<span class="sd">        the Aggregate object&#39;s default alias.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">distinct_fields</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s">&quot;aggregate() + distinct(fields) not implemented.&quot;</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">args</span><span class="p">:</span>
            <span class="n">kwargs</span><span class="p">[</span><span class="n">arg</span><span class="o">.</span><span class="n">default_alias</span><span class="p">]</span> <span class="o">=</span> <span class="n">arg</span>

        <span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">()</span>
        <span class="n">force_subq</span> <span class="o">=</span> <span class="n">query</span><span class="o">.</span><span class="n">low_mark</span> <span class="o">!=</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">query</span><span class="o">.</span><span class="n">high_mark</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span>
        <span class="k">for</span> <span class="p">(</span><span class="n">alias</span><span class="p">,</span> <span class="n">aggregate_expr</span><span class="p">)</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="n">query</span><span class="o">.</span><span class="n">add_aggregate</span><span class="p">(</span><span class="n">aggregate_expr</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">alias</span><span class="p">,</span>
                                <span class="n">is_summary</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">query</span><span class="o">.</span><span class="n">get_aggregation</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">,</span> <span class="n">force_subq</span><span class="o">=</span><span class="n">force_subq</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">count</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Performs a SELECT COUNT() and returns the number of records as an</span>
<span class="sd">        integer.</span>

<span class="sd">        If the QuerySet is already fully cached this simply returns the length</span>
<span class="sd">        of the cached results set to avoid multiple SELECT COUNT(*) calls.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">)</span>

        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_count</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">get</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Performs the query and returns a single object matching the given</span>
<span class="sd">        keyword arguments.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">():</span>
            <span class="n">clone</span> <span class="o">=</span> <span class="n">clone</span><span class="o">.</span><span class="n">order_by</span><span class="p">()</span>
        <span class="k">if</span> <span class="p">(</span><span class="ow">not</span> <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_for_update</span> <span class="ow">or</span>
                <span class="n">connections</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">]</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">supports_select_for_update_with_limit</span><span class="p">):</span>
            <span class="n">clone</span> <span class="o">=</span> <span class="n">clone</span><span class="p">[:</span><span class="n">MAX_GET_RESULTS</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span>
        <span class="n">num</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">clone</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">num</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">clone</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">num</span><span class="p">:</span>
            <span class="k">raise</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">(</span>
                <span class="s">&quot;</span><span class="si">%s</span><span class="s"> matching query does not exist.&quot;</span> <span class="o">%</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">object_name</span><span class="p">)</span>
        <span class="k">raise</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">MultipleObjectsReturned</span><span class="p">(</span>
            <span class="s">&quot;get() returned more than one </span><span class="si">%s</span><span class="s"> -- it returned </span><span class="si">%s</span><span class="s">!&quot;</span> <span class="o">%</span> <span class="p">(</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">object_name</span><span class="p">,</span>
                <span class="n">num</span> <span class="k">if</span> <span class="n">num</span> <span class="o">&lt;=</span> <span class="n">MAX_GET_RESULTS</span> <span class="k">else</span> <span class="s">&#39;more than </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">MAX_GET_RESULTS</span>
            <span class="p">)</span>
        <span class="p">)</span>

    <span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Creates a new object with the given kwargs, saving it to the database</span>
<span class="sd">        and returning the created object.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">force_insert</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">bulk_create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">objs</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Inserts each of the instances into the database. This does *not* call</span>
<span class="sd">        save() on each of the instances, does not send any pre/post save</span>
<span class="sd">        signals, and does not set the primary key attribute if it is an</span>
<span class="sd">        autoincrement field.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c"># So this case is fun. When you bulk insert you don&#39;t get the primary</span>
        <span class="c"># keys back (if it&#39;s an autoincrement), so you can&#39;t insert into the</span>
        <span class="c"># child tables which references this. There are two workarounds, 1)</span>
        <span class="c"># this could be implemented if you didn&#39;t have an autoincrement pk,</span>
        <span class="c"># and 2) you could do it by doing O(n) normal inserts into the parent</span>
        <span class="c"># tables to get the primary keys back, and then doing a single bulk</span>
        <span class="c"># insert into the childmost table. Some databases might allow doing</span>
        <span class="c"># this by using RETURNING clause for the insert query. We&#39;re punting</span>
        <span class="c"># on these for now because they are relatively rare cases.</span>
        <span class="k">assert</span> <span class="n">batch_size</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">batch_size</span> <span class="o">&gt;</span> <span class="mi">0</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">parents</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;Can&#39;t bulk create an inherited model&quot;</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">objs</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">objs</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">connection</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">]</span>
        <span class="n">fields</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">local_concrete_fields</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">commit_on_success_unless_managed</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">):</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">connection</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">can_combine_inserts_with_and_without_auto_increment_pk</span>
                    <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">has_auto_field</span><span class="p">):</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_batched_insert</span><span class="p">(</span><span class="n">objs</span><span class="p">,</span> <span class="n">fields</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">objs_with_pk</span><span class="p">,</span> <span class="n">objs_without_pk</span> <span class="o">=</span> <span class="n">partition</span><span class="p">(</span><span class="k">lambda</span> <span class="n">o</span><span class="p">:</span> <span class="n">o</span><span class="o">.</span><span class="n">pk</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">,</span> <span class="n">objs</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">objs_with_pk</span><span class="p">:</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_batched_insert</span><span class="p">(</span><span class="n">objs_with_pk</span><span class="p">,</span> <span class="n">fields</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">objs_without_pk</span><span class="p">:</span>
                    <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">fields</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">AutoField</span><span class="p">)]</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_batched_insert</span><span class="p">(</span><span class="n">objs_without_pk</span><span class="p">,</span> <span class="n">fields</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">objs</span>

    <span class="k">def</span> <span class="nf">get_or_create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Looks up an object with the given kwargs, creating one if necessary.</span>
<span class="sd">        Returns a tuple of (object, created), where created is a boolean</span>
<span class="sd">        specifying whether an object was created.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">lookup</span><span class="p">,</span> <span class="n">params</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_extract_model_params</span><span class="p">(</span><span class="n">defaults</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="o">**</span><span class="n">lookup</span><span class="p">),</span> <span class="bp">False</span>
        <span class="k">except</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_create_object_from_params</span><span class="p">(</span><span class="n">lookup</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">update_or_create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Looks up an object with the given kwargs, updating one with defaults</span>
<span class="sd">        if it exists, otherwise creates a new one.</span>
<span class="sd">        Returns a tuple (object, created), where created is a boolean</span>
<span class="sd">        specifying whether an object was created.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">defaults</span> <span class="o">=</span> <span class="n">defaults</span> <span class="ow">or</span> <span class="p">{}</span>
        <span class="n">lookup</span><span class="p">,</span> <span class="n">params</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_extract_model_params</span><span class="p">(</span><span class="n">defaults</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="o">**</span><span class="n">lookup</span><span class="p">)</span>
        <span class="k">except</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
            <span class="n">obj</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_create_object_from_params</span><span class="p">(</span><span class="n">lookup</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">created</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">obj</span><span class="p">,</span> <span class="n">created</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">six</span><span class="o">.</span><span class="n">iteritems</span><span class="p">(</span><span class="n">defaults</span><span class="p">):</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>

        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">):</span>
            <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">obj</span><span class="p">,</span> <span class="bp">False</span>

    <span class="k">def</span> <span class="nf">_create_object_from_params</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">lookup</span><span class="p">,</span> <span class="n">params</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Tries to create an object using passed params.</span>
<span class="sd">        Used by get_or_create and update_or_create</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">):</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">force_insert</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">obj</span><span class="p">,</span> <span class="bp">True</span>
        <span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
            <span class="n">exc_info</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="o">**</span><span class="n">lookup</span><span class="p">),</span> <span class="bp">False</span>
            <span class="k">except</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
                <span class="k">pass</span>
            <span class="n">six</span><span class="o">.</span><span class="n">reraise</span><span class="p">(</span><span class="o">*</span><span class="n">exc_info</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_extract_model_params</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">defaults</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Prepares `lookup` (kwargs that are valid model attributes), `params`</span>
<span class="sd">        (for creating a model instance) based on given kwargs; for use by</span>
<span class="sd">        get_or_create and update_or_create.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">defaults</span> <span class="o">=</span> <span class="n">defaults</span> <span class="ow">or</span> <span class="p">{}</span>
        <span class="n">lookup</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">f</span><span class="o">.</span><span class="n">attname</span> <span class="ow">in</span> <span class="n">lookup</span><span class="p">:</span>
                <span class="n">lookup</span><span class="p">[</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
        <span class="n">params</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="k">if</span> <span class="n">LOOKUP_SEP</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">k</span><span class="p">)</span>
        <span class="n">params</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">defaults</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">lookup</span><span class="p">,</span> <span class="n">params</span>

    <span class="k">def</span> <span class="nf">_earliest_or_latest</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">field_name</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">direction</span><span class="o">=</span><span class="s">&quot;-&quot;</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns the latest object, according to the model&#39;s</span>
<span class="sd">        &#39;get_latest_by&#39; option or optional given field_name.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">order_by</span> <span class="o">=</span> <span class="n">field_name</span> <span class="ow">or</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="p">,</span> <span class="s">&#39;get_latest_by&#39;</span><span class="p">)</span>
        <span class="k">assert</span> <span class="nb">bool</span><span class="p">(</span><span class="n">order_by</span><span class="p">),</span> <span class="s">&quot;earliest() and latest() require either a &quot;</span>\
            <span class="s">&quot;field_name parameter or &#39;get_latest_by&#39; in the model&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot change a query once a slice has been taken.&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_limits</span><span class="p">(</span><span class="n">high</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_ordering</span><span class="p">(</span><span class="n">force_empty</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_ordering</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%s%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">order_by</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">earliest</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">field_name</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_earliest_or_latest</span><span class="p">(</span><span class="n">field_name</span><span class="o">=</span><span class="n">field_name</span><span class="p">,</span> <span class="n">direction</span><span class="o">=</span><span class="s">&quot;&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">latest</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">field_name</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_earliest_or_latest</span><span class="p">(</span><span class="n">field_name</span><span class="o">=</span><span class="n">field_name</span><span class="p">,</span> <span class="n">direction</span><span class="o">=</span><span class="s">&quot;-&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">first</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns the first object of a query, returns None if no match is found.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">qs</span> <span class="o">=</span> <span class="bp">self</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">ordered</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;pk&#39;</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">qs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">None</span>

    <span class="k">def</span> <span class="nf">last</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns the last object of a query, returns None if no match is found.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">qs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">ordered</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-pk&#39;</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">qs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">None</span>

    <span class="k">def</span> <span class="nf">in_bulk</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">id_list</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a dictionary mapping each of the given IDs to the object with</span>
<span class="sd">        that ID.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot use &#39;limit&#39; or &#39;offset&#39; with in_bulk&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">id_list</span><span class="p">:</span>
            <span class="k">return</span> <span class="p">{}</span>
        <span class="n">qs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk__in</span><span class="o">=</span><span class="n">id_list</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">dict</span><span class="p">((</span><span class="n">obj</span><span class="o">.</span><span class="n">_get_pk_val</span><span class="p">(),</span> <span class="n">obj</span><span class="p">)</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">qs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">delete</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Deletes the records in the current QuerySet.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot use &#39;limit&#39; or &#39;offset&#39; with delete.&quot;</span>

        <span class="n">del_query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>

        <span class="c"># The delete is actually 2 queries - one to find related objects,</span>
        <span class="c"># and one to delete. Make sure that the discovery of related</span>
        <span class="c"># objects is performed on the same database as the deletion.</span>
        <span class="n">del_query</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>

        <span class="c"># Disable non-supported fields.</span>
        <span class="n">del_query</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_for_update</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="n">del_query</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_related</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="n">del_query</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_ordering</span><span class="p">(</span><span class="n">force_empty</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

        <span class="n">collector</span> <span class="o">=</span> <span class="n">Collector</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="n">del_query</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>
        <span class="n">collector</span><span class="o">.</span><span class="n">collect</span><span class="p">(</span><span class="n">del_query</span><span class="p">)</span>
        <span class="n">collector</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>

        <span class="c"># Clear the result cache, in case this QuerySet gets reused.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="n">delete</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="n">delete</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">_raw_delete</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">using</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Deletes objects found from the given queryset in single direct SQL</span>
<span class="sd">        query. No signals are sent, and there is no protection for cascades.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">sql</span><span class="o">.</span><span class="n">DeleteQuery</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">)</span><span class="o">.</span><span class="n">delete_qs</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">using</span><span class="p">)</span>
    <span class="n">_raw_delete</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Updates all elements in the current QuerySet, setting all the given</span>
<span class="sd">        fields to the appropriate values.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot update a query once a slice has been taken.&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">(</span><span class="n">sql</span><span class="o">.</span><span class="n">UpdateQuery</span><span class="p">)</span>
        <span class="n">query</span><span class="o">.</span><span class="n">add_update_values</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">commit_on_success_unless_managed</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">):</span>
            <span class="n">rows</span> <span class="o">=</span> <span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">execute_sql</span><span class="p">(</span><span class="n">CURSOR</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="k">return</span> <span class="n">rows</span>
    <span class="n">update</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">_update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        A version of update that accepts field objects instead of field names.</span>
<span class="sd">        Used primarily for model saving and not intended for use by general</span>
<span class="sd">        code (it requires too much poking around at model internals to be</span>
<span class="sd">        useful at that level).</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot update a query once a slice has been taken.&quot;</span>
        <span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">(</span><span class="n">sql</span><span class="o">.</span><span class="n">UpdateQuery</span><span class="p">)</span>
        <span class="n">query</span><span class="o">.</span><span class="n">add_update_fields</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="k">return</span> <span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">execute_sql</span><span class="p">(</span><span class="n">CURSOR</span><span class="p">)</span>
    <span class="n">_update</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="n">_update</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">False</span>

    <span class="k">def</span> <span class="nf">exists</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">has_results</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">bool</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_prefetch_related_objects</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># This method can only be called once the result cache has been filled.</span>
        <span class="n">prefetch_related_objects</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_done</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="c">##################################################</span>
    <span class="c"># PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #</span>
    <span class="c">##################################################</span>

    <span class="k">def</span> <span class="nf">raw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">raw_query</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">translations</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">using</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">using</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>
        <span class="k">return</span> <span class="n">RawQuerySet</span><span class="p">(</span><span class="n">raw_query</span><span class="p">,</span> <span class="n">model</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span>
                <span class="n">params</span><span class="o">=</span><span class="n">params</span><span class="p">,</span> <span class="n">translations</span><span class="o">=</span><span class="n">translations</span><span class="p">,</span>
                <span class="n">using</span><span class="o">=</span><span class="n">using</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">values</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">ValuesQuerySet</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">_fields</span><span class="o">=</span><span class="n">fields</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">values_list</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">flat</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s">&#39;flat&#39;</span><span class="p">,</span> <span class="bp">False</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">kwargs</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&#39;Unexpected keyword arguments to values_list: </span><span class="si">%s</span><span class="s">&#39;</span>
                    <span class="o">%</span> <span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">kwargs</span><span class="p">),))</span>
        <span class="k">if</span> <span class="n">flat</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&quot;&#39;flat&#39; is not valid when values_list is called with more than one field.&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">ValuesListQuerySet</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="n">flat</span><span class="p">,</span>
                <span class="n">_fields</span><span class="o">=</span><span class="n">fields</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">dates</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">field_name</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="n">order</span><span class="o">=</span><span class="s">&#39;ASC&#39;</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a list of date objects representing all available dates for</span>
<span class="sd">        the given field_name, scoped to &#39;kind&#39;.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="n">kind</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&quot;year&quot;</span><span class="p">,</span> <span class="s">&quot;month&quot;</span><span class="p">,</span> <span class="s">&quot;day&quot;</span><span class="p">),</span> \
            <span class="s">&quot;&#39;kind&#39; must be one of &#39;year&#39;, &#39;month&#39; or &#39;day&#39;.&quot;</span>
        <span class="k">assert</span> <span class="n">order</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;ASC&#39;</span><span class="p">,</span> <span class="s">&#39;DESC&#39;</span><span class="p">),</span> \
            <span class="s">&quot;&#39;order&#39; must be either &#39;ASC&#39; or &#39;DESC&#39;.&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">DateQuerySet</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
             <span class="n">_field_name</span><span class="o">=</span><span class="n">field_name</span><span class="p">,</span> <span class="n">_kind</span><span class="o">=</span><span class="n">kind</span><span class="p">,</span> <span class="n">_order</span><span class="o">=</span><span class="n">order</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">datetimes</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">field_name</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="n">order</span><span class="o">=</span><span class="s">&#39;ASC&#39;</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a list of datetime objects representing all available</span>
<span class="sd">        datetimes for the given field_name, scoped to &#39;kind&#39;.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="n">kind</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&quot;year&quot;</span><span class="p">,</span> <span class="s">&quot;month&quot;</span><span class="p">,</span> <span class="s">&quot;day&quot;</span><span class="p">,</span> <span class="s">&quot;hour&quot;</span><span class="p">,</span> <span class="s">&quot;minute&quot;</span><span class="p">,</span> <span class="s">&quot;second&quot;</span><span class="p">),</span> \
            <span class="s">&quot;&#39;kind&#39; must be one of &#39;year&#39;, &#39;month&#39;, &#39;day&#39;, &#39;hour&#39;, &#39;minute&#39; or &#39;second&#39;.&quot;</span>
        <span class="k">assert</span> <span class="n">order</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;ASC&#39;</span><span class="p">,</span> <span class="s">&#39;DESC&#39;</span><span class="p">),</span> \
            <span class="s">&quot;&#39;order&#39; must be either &#39;ASC&#39; or &#39;DESC&#39;.&quot;</span>
        <span class="k">if</span> <span class="n">settings</span><span class="o">.</span><span class="n">USE_TZ</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">tzinfo</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
                <span class="n">tzinfo</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">get_current_timezone</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">tzinfo</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">DateTimeQuerySet</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
                <span class="n">_field_name</span><span class="o">=</span><span class="n">field_name</span><span class="p">,</span> <span class="n">_kind</span><span class="o">=</span><span class="n">kind</span><span class="p">,</span> <span class="n">_order</span><span class="o">=</span><span class="n">order</span><span class="p">,</span> <span class="n">_tzinfo</span><span class="o">=</span><span class="n">tzinfo</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">none</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns an empty QuerySet.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_empty</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="c">##################################################################</span>
    <span class="c"># PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #</span>
    <span class="c">##################################################################</span>

    <span class="k">def</span> <span class="nf">all</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet that is a copy of the current one. This allows a</span>
<span class="sd">        QuerySet to proxy for a model manager in some cases.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance with the args ANDed to the existing</span>
<span class="sd">        set.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_filter_or_exclude</span><span class="p">(</span><span class="bp">False</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">exclude</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance with NOT (args) ANDed to the existing</span>
<span class="sd">        set.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_filter_or_exclude</span><span class="p">(</span><span class="bp">True</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_filter_or_exclude</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">negate</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">args</span> <span class="ow">or</span> <span class="n">kwargs</span><span class="p">:</span>
            <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
                <span class="s">&quot;Cannot filter a query once a slice has been taken.&quot;</span>

        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">negate</span><span class="p">:</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_q</span><span class="p">(</span><span class="o">~</span><span class="n">Q</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_q</span><span class="p">(</span><span class="n">Q</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">complex_filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">filter_obj</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance with filter_obj added to the filters.</span>

<span class="sd">        filter_obj can be a Q object (or anything with an add_to_query()</span>
<span class="sd">        method) or a dictionary of keyword lookup arguments.</span>

<span class="sd">        This exists to support framework features such as &#39;limit_choices_to&#39;,</span>
<span class="sd">        and usually it will be more natural to use other methods.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">filter_obj</span><span class="p">,</span> <span class="n">Q</span><span class="p">)</span> <span class="ow">or</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">filter_obj</span><span class="p">,</span> <span class="s">&#39;add_to_query&#39;</span><span class="p">):</span>
            <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_q</span><span class="p">(</span><span class="n">filter_obj</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">clone</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_filter_or_exclude</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="o">**</span><span class="n">filter_obj</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">select_for_update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nowait</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance that will select objects with a</span>
<span class="sd">        FOR UPDATE lock.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_for_update</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_for_update_nowait</span> <span class="o">=</span> <span class="n">nowait</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">select_related</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance that will select related objects.</span>

<span class="sd">        If fields are specified, they must be ForeignKey fields and only those</span>
<span class="sd">        related objects are included in the selection.</span>

<span class="sd">        If select_related(None) is called, the list is cleared.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">fields</span> <span class="o">==</span> <span class="p">(</span><span class="bp">None</span><span class="p">,):</span>
            <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_related</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="k">elif</span> <span class="n">fields</span><span class="p">:</span>
            <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_select_related</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_related</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">prefetch_related</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">lookups</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance that will prefetch the specified</span>
<span class="sd">        Many-To-One and Many-To-Many related objects when the QuerySet is</span>
<span class="sd">        evaluated.</span>

<span class="sd">        When prefetch_related() is called more than once, the list of lookups to</span>
<span class="sd">        prefetch is appended to. If prefetch_related(None) is called, the list</span>
<span class="sd">        is cleared.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">lookups</span> <span class="o">==</span> <span class="p">(</span><span class="bp">None</span><span class="p">,):</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">lookups</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">annotate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Return a query set in which the returned objects have been annotated</span>
<span class="sd">        with data aggregated from related fields.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">args</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">arg</span><span class="o">.</span><span class="n">default_alias</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;The named annotation &#39;</span><span class="si">%s</span><span class="s">&#39; conflicts with the &quot;</span>
                                 <span class="s">&quot;default name for another annotation.&quot;</span>
                                 <span class="o">%</span> <span class="n">arg</span><span class="o">.</span><span class="n">default_alias</span><span class="p">)</span>
            <span class="n">kwargs</span><span class="p">[</span><span class="n">arg</span><span class="o">.</span><span class="n">default_alias</span><span class="p">]</span> <span class="o">=</span> <span class="n">arg</span>

        <span class="n">names</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&#39;_fields&#39;</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">names</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">names</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_all_field_names</span><span class="p">())</span>
        <span class="k">for</span> <span class="n">aggregate</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">aggregate</span> <span class="ow">in</span> <span class="n">names</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;The annotation &#39;</span><span class="si">%s</span><span class="s">&#39; conflicts with a field on &quot;</span>
                    <span class="s">&quot;the model.&quot;</span> <span class="o">%</span> <span class="n">aggregate</span><span class="p">)</span>

        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>

        <span class="n">obj</span><span class="o">.</span><span class="n">_setup_aggregate_query</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">kwargs</span><span class="p">))</span>

        <span class="c"># Add the aggregates to the query</span>
        <span class="k">for</span> <span class="p">(</span><span class="n">alias</span><span class="p">,</span> <span class="n">aggregate_expr</span><span class="p">)</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_aggregate</span><span class="p">(</span><span class="n">aggregate_expr</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">alias</span><span class="p">,</span>
                <span class="n">is_summary</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">order_by</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">field_names</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance with the ordering changed.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot reorder a query once a slice has been taken.&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_ordering</span><span class="p">(</span><span class="n">force_empty</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_ordering</span><span class="p">(</span><span class="o">*</span><span class="n">field_names</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">distinct</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">field_names</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new QuerySet instance that will select only distinct results.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot create distinct fields once a slice has been taken.&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_distinct_fields</span><span class="p">(</span><span class="o">*</span><span class="n">field_names</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">obj</span>

    <span class="k">def</span> <span class="nf">extra</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">select</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">where</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">tables</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
              <span class="n">order_by</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">select_params</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Adds extra SQL fragments to the query.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">can_filter</span><span class="p">(),</span> \
            <span class="s">&quot;Cannot change a query once a slice has been taken&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_extra</span><span class="p">(</span><span class="n">select</span><span class="p">,</span> <span class="n">select_params</span><span class="p">,</span> <span class="n">where</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">tables</span><span class="p">,</span> <span class="n">order_by</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Reverses the ordering of the QuerySet.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">standard_ordering</span> <span class="o">=</span> <span class="ow">not</span> <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">standard_ordering</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">defer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Defers the loading of data for certain fields until they are accessed.</span>
<span class="sd">        The set of fields to defer is added to any existing set of deferred</span>
<span class="sd">        fields. The only exception to this is if None is passed in as the only</span>
<span class="sd">        parameter, in which case all deferrals are removed (None acts as a</span>
<span class="sd">        reset option).</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">fields</span> <span class="o">==</span> <span class="p">(</span><span class="bp">None</span><span class="p">,):</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_deferred_loading</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_deferred_loading</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">only</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Essentially, the opposite of defer. Only the fields passed into this</span>
<span class="sd">        method and that are not already specified as deferred are loaded</span>
<span class="sd">        immediately when the queryset is evaluated.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="n">fields</span> <span class="o">==</span> <span class="p">(</span><span class="bp">None</span><span class="p">,):</span>
            <span class="c"># Can only pass None to defer(), not only(), as the rest option.</span>
            <span class="c"># That won&#39;t stop people trying to do this, so let&#39;s be explicit.</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&quot;Cannot pass None as an argument to only().&quot;</span><span class="p">)</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">clone</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_immediate_loading</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="k">def</span> <span class="nf">using</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">alias</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Selects which database this QuerySet should execute its query against.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="n">clone</span><span class="o">.</span><span class="n">_db</span> <span class="o">=</span> <span class="n">alias</span>
        <span class="k">return</span> <span class="n">clone</span>

    <span class="c">###################################</span>
    <span class="c"># PUBLIC INTROSPECTION ATTRIBUTES #</span>
    <span class="c">###################################</span>

<div class="viewcode-block" id="QuerySet.ordered"><a class="viewcode-back" href="../../../../ref/models/querysets.html#django.db.models.query.QuerySet.ordered">[docs]</a>    <span class="k">def</span> <span class="nf">ordered</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns True if the QuerySet is ordered -- i.e. has an order_by()</span>
<span class="sd">        clause or a default ordering on the model.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">extra_order_by</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">order_by</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">True</span>
        <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">default_ordering</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_meta</span><span class="p">()</span><span class="o">.</span><span class="n">ordering</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">True</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">False</span></div>
    <span class="n">ordered</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">ordered</span><span class="p">)</span>

    <span class="nd">@property</span>
<div class="viewcode-block" id="QuerySet.db"><a class="viewcode-back" href="../../../../ref/models/querysets.html#django.db.models.query.QuerySet.db">[docs]</a>    <span class="k">def</span> <span class="nf">db</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Return the database that will be used if this query is executed now&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_db</span> <span class="ow">or</span> <span class="n">router</span><span class="o">.</span><span class="n">db_for_write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">_hints</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_db</span> <span class="ow">or</span> <span class="n">router</span><span class="o">.</span><span class="n">db_for_read</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">_hints</span><span class="p">)</span>

    <span class="c">###################</span>
    <span class="c"># PRIVATE METHODS #</span>
    <span class="c">###################</span>
</div>
    <span class="k">def</span> <span class="nf">_insert</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">objs</span><span class="p">,</span> <span class="n">fields</span><span class="p">,</span> <span class="n">return_id</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Inserts a new record for the given model. This provides an interface to</span>
<span class="sd">        the InsertQuery class and is how Model.save() is implemented.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">if</span> <span class="n">using</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">using</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>
        <span class="n">query</span> <span class="o">=</span> <span class="n">sql</span><span class="o">.</span><span class="n">InsertQuery</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">)</span>
        <span class="n">query</span><span class="o">.</span><span class="n">insert_values</span><span class="p">(</span><span class="n">fields</span><span class="p">,</span> <span class="n">objs</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="n">raw</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="n">using</span><span class="p">)</span><span class="o">.</span><span class="n">execute_sql</span><span class="p">(</span><span class="n">return_id</span><span class="p">)</span>
    <span class="n">_insert</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="n">_insert</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">False</span>

    <span class="k">def</span> <span class="nf">_batched_insert</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">objs</span><span class="p">,</span> <span class="n">fields</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        A little helper method for bulk_insert to insert the bulk one batch</span>
<span class="sd">        at a time. Inserts recursively a batch from the front of the bulk and</span>
<span class="sd">        then _batched_insert() the remaining objects again.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">objs</span><span class="p">:</span>
            <span class="k">return</span>
        <span class="n">ops</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">]</span><span class="o">.</span><span class="n">ops</span>
        <span class="n">batch_size</span> <span class="o">=</span> <span class="p">(</span><span class="n">batch_size</span> <span class="ow">or</span> <span class="nb">max</span><span class="p">(</span><span class="n">ops</span><span class="o">.</span><span class="n">bulk_batch_size</span><span class="p">(</span><span class="n">fields</span><span class="p">,</span> <span class="n">objs</span><span class="p">),</span> <span class="mi">1</span><span class="p">))</span>
        <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="p">[</span><span class="n">objs</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span> <span class="o">+</span> <span class="n">batch_size</span><span class="p">]</span>
                      <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">objs</span><span class="p">),</span> <span class="n">batch_size</span><span class="p">)]:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_base_manager</span><span class="o">.</span><span class="n">_insert</span><span class="p">(</span><span class="n">batch</span><span class="p">,</span> <span class="n">fields</span><span class="o">=</span><span class="n">fields</span><span class="p">,</span>
                                             <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">klass</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">klass</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">klass</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span>
        <span class="k">elif</span> <span class="ow">not</span> <span class="nb">issubclass</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="p">,</span> <span class="n">klass</span><span class="p">):</span>
            <span class="n">base_queryset_class</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&#39;_base_queryset_class&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="p">)</span>
            <span class="n">class_bases</span> <span class="o">=</span> <span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="n">base_queryset_class</span><span class="p">)</span>
            <span class="n">class_dict</span> <span class="o">=</span> <span class="p">{</span>
                <span class="s">&#39;_base_queryset_class&#39;</span><span class="p">:</span> <span class="n">base_queryset_class</span><span class="p">,</span>
                <span class="s">&#39;_specialized_queryset_class&#39;</span><span class="p">:</span> <span class="n">klass</span><span class="p">,</span>
            <span class="p">}</span>
            <span class="n">klass</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">class_bases</span><span class="p">,</span> <span class="n">class_dict</span><span class="p">)</span>

        <span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_sticky_filter</span><span class="p">:</span>
            <span class="n">query</span><span class="o">.</span><span class="n">filter_is_sticky</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">c</span> <span class="o">=</span> <span class="n">klass</span><span class="p">(</span><span class="n">model</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">query</span><span class="o">=</span><span class="n">query</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_db</span><span class="p">,</span> <span class="n">hints</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_hints</span><span class="p">)</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_for_write</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_for_write</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span><span class="p">[:]</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_known_related_objects</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_known_related_objects</span>
        <span class="n">c</span><span class="o">.</span><span class="n">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">setup</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s">&#39;_setup_query&#39;</span><span class="p">):</span>
            <span class="n">c</span><span class="o">.</span><span class="n">_setup_query</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">c</span>

    <span class="k">def</span> <span class="nf">_fetch_all</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">iterator</span><span class="p">())</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span> <span class="ow">and</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_done</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_prefetch_related_objects</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">_next_is_sticky</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Indicates that the next filter call and the one following that should</span>
<span class="sd">        be treated as a single filter. This is only important when it comes to</span>
<span class="sd">        determining when to reuse tables for many-to-many filters. Required so</span>
<span class="sd">        that we can filter naturally on the results of related managers.</span>

<span class="sd">        This doesn&#39;t return a clone of the current QuerySet (it returns</span>
<span class="sd">        &quot;self&quot;). The method is only used internally and should be immediately</span>
<span class="sd">        followed by a filter() that does create a clone.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_sticky_filter</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">_merge_sanity_check</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Checks that we are merging two comparable QuerySet classes. By default</span>
<span class="sd">        this does nothing, but see the ValuesQuerySet for an example of where</span>
<span class="sd">        it&#39;s useful.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">_merge_known_related_objects</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Keep track of all known related objects from either QuerySet instance.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">for</span> <span class="n">field</span><span class="p">,</span> <span class="n">objects</span> <span class="ow">in</span> <span class="n">other</span><span class="o">.</span><span class="n">_known_related_objects</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_known_related_objects</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">field</span><span class="p">,</span> <span class="p">{})</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">objects</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_setup_aggregate_query</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">aggregates</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Prepare the query for computing a result that contains aggregate annotations.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">opts</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">group_by</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span><span class="o">.</span><span class="n">attname</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">opts</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">]</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_fields</span><span class="p">(</span><span class="n">field_names</span><span class="p">,</span> <span class="bp">False</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_group_by</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">_prepare</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">_as_sql</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns the internal query&#39;s SQL and parameters (as a tuple).</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&quot;pk&quot;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">obj</span><span class="o">.</span><span class="n">_db</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">connection</span> <span class="o">==</span> <span class="n">connections</span><span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">_db</span><span class="p">]:</span>
            <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="n">connection</span><span class="o">=</span><span class="n">connection</span><span class="p">)</span><span class="o">.</span><span class="n">as_nested_sql</span><span class="p">()</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;Can&#39;t do subqueries with queries on different DBs.&quot;</span><span class="p">)</span>

    <span class="c"># When used as part of a nested query, a queryset will never be an &quot;always</span>
    <span class="c"># empty&quot; result.</span>
    <span class="n">value_annotation</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">_add_hints</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Update hinting information for later use by Routers</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c"># If there is any hinting information, add it to what we already know.</span>
        <span class="c"># If we have a new hint for an existing key, overwrite with the new value.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_hints</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">hints</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_has_filters</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Checks if this QuerySet has any filtering going on. Note that this</span>
<span class="sd">        isn&#39;t equivalent for checking if all objects are present in results,</span>
<span class="sd">        for example qs[1:]._has_filters() -&gt; False.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">has_filters</span><span class="p">()</span>

</div>
<span class="k">class</span> <span class="nc">InstanceCheckMeta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__instancecheck__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">instance</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">instance</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">is_empty</span><span class="p">()</span>


<span class="k">class</span> <span class="nc">EmptyQuerySet</span><span class="p">(</span><span class="n">six</span><span class="o">.</span><span class="n">with_metaclass</span><span class="p">(</span><span class="n">InstanceCheckMeta</span><span class="p">)):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Marker class usable for checking if a queryset is empty by .none():</span>
<span class="sd">        isinstance(qs.none(), EmptyQuerySet) -&gt; True</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&quot;EmptyQuerySet can&#39;t be instantiated&quot;</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">ValuesQuerySet</span><span class="p">(</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">ValuesQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="c"># select_related isn&#39;t supported in values(). (FIXME -#3358)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select_related</span> <span class="o">=</span> <span class="bp">False</span>

        <span class="c"># QuerySet.clone() will also set up the _fields attribute with the</span>
        <span class="c"># names of the model fields to select.</span>

    <span class="k">def</span> <span class="nf">only</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s">&quot;ValuesQuerySet does not implement only()&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">defer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">fields</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s">&quot;ValuesQuerySet does not implement defer()&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Purge any extra columns that haven&#39;t been explicitly asked for</span>
        <span class="n">extra_names</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">extra_select</span><span class="p">)</span>
        <span class="n">field_names</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span>
        <span class="n">aggregate_names</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">aggregate_select</span><span class="p">)</span>

        <span class="n">names</span> <span class="o">=</span> <span class="n">extra_names</span> <span class="o">+</span> <span class="n">field_names</span> <span class="o">+</span> <span class="n">aggregate_names</span>

        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">():</span>
            <span class="k">yield</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">names</span><span class="p">,</span> <span class="n">row</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">delete</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># values().delete() doesn&#39;t work currently - make sure it raises an</span>
        <span class="c"># user friendly error.</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&quot;Queries with .values() or .values_list() applied &quot;</span>
                        <span class="s">&quot;can&#39;t be deleted&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_setup_query</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Constructs the field_names list that the values query will be</span>
<span class="sd">        retrieving.</span>

<span class="sd">        Called by the _clone() method after initializing the rest of the</span>
<span class="sd">        instance.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_deferred_loading</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_select_fields</span><span class="p">()</span>

        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">_extra</span> <span class="ow">and</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">_aggregates</span><span class="p">:</span>
                <span class="c"># Short cut - if there are no extra or aggregates, then</span>
                <span class="c"># the values() clause must be just field names.</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">default_cols</span> <span class="o">=</span> <span class="bp">False</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span> <span class="o">=</span> <span class="p">[]</span>
                <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">:</span>
                    <span class="c"># we inspect the full extra_select list since we might</span>
                    <span class="c"># be adding back an extra select item that we hadn&#39;t</span>
                    <span class="c"># had selected previously.</span>
                    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">_extra</span> <span class="ow">and</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">_extra</span><span class="p">:</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
                    <span class="k">elif</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">aggregate_select</span><span class="p">:</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
                    <span class="k">else</span><span class="p">:</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c"># Default to all fields.</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span><span class="o">.</span><span class="n">attname</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">]</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="o">=</span> <span class="bp">None</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_extra_mask</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_fields</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">field_names</span><span class="p">,</span> <span class="bp">True</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_aggregate_mask</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">klass</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Cloning a ValuesQuerySet preserves the current fields.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">c</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">ValuesQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s">&#39;_fields&#39;</span><span class="p">):</span>
            <span class="c"># Only clone self._fields if _fields wasn&#39;t passed into the cloning</span>
            <span class="c"># call directly.</span>
            <span class="n">c</span><span class="o">.</span><span class="n">_fields</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">[:]</span>
        <span class="n">c</span><span class="o">.</span><span class="n">field_names</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span>
        <span class="n">c</span><span class="o">.</span><span class="n">extra_names</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span>
        <span class="n">c</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span>
        <span class="k">if</span> <span class="n">setup</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s">&#39;_setup_query&#39;</span><span class="p">):</span>
            <span class="n">c</span><span class="o">.</span><span class="n">_setup_query</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">c</span>

    <span class="k">def</span> <span class="nf">_merge_sanity_check</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">ValuesQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_merge_sanity_check</span><span class="p">(</span><span class="n">other</span><span class="p">)</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">extra_names</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">set</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">extra_names</span><span class="p">)</span> <span class="ow">or</span>
                <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">field_names</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">set</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">field_names</span><span class="p">)</span> <span class="ow">or</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="o">!=</span> <span class="n">other</span><span class="o">.</span><span class="n">aggregate_names</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&quot;Merging &#39;</span><span class="si">%s</span><span class="s">&#39; classes must involve the same values in each case.&quot;</span>
                    <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_setup_aggregate_query</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">aggregates</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Prepare the query for computing a result that contains aggregate annotations.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_group_by</span><span class="p">()</span>

        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">aggregates</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">set_aggregate_mask</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">aggregate_names</span><span class="p">)</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">ValuesQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_setup_aggregate_query</span><span class="p">(</span><span class="n">aggregates</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_as_sql</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        For ValuesQuerySet (and subclasses like ValuesListQuerySet), they can</span>
<span class="sd">        only be used as nested queries if they&#39;re already set up to select only</span>
<span class="sd">        a single field (in which case, that is the field column that is</span>
<span class="sd">        returned). This differs from QuerySet.as_sql(), where the column to</span>
<span class="sd">        select is set up by Django.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)</span> <span class="ow">or</span>
                <span class="p">(</span><span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)):</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&#39;Cannot use a multi-field </span><span class="si">%s</span><span class="s"> as a filter value.&#39;</span>
                    <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">)</span>

        <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">obj</span><span class="o">.</span><span class="n">_db</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">connection</span> <span class="o">==</span> <span class="n">connections</span><span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">_db</span><span class="p">]:</span>
            <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="n">connection</span><span class="o">=</span><span class="n">connection</span><span class="p">)</span><span class="o">.</span><span class="n">as_nested_sql</span><span class="p">()</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;Can&#39;t do subqueries with queries on different DBs.&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_prepare</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Validates that we aren&#39;t trying to do a query like</span>
<span class="sd">        value__in=qs.values(&#39;value1&#39;, &#39;value2&#39;), which isn&#39;t valid.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)</span> <span class="ow">or</span>
                <span class="p">(</span><span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)):</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&#39;Cannot use a multi-field </span><span class="si">%s</span><span class="s"> as a filter value.&#39;</span>
                    <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span>


<span class="k">class</span> <span class="nc">ValuesListQuerySet</span><span class="p">(</span><span class="n">ValuesQuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">flat</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">():</span>
                <span class="k">yield</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">elif</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">extra_select</span> <span class="ow">and</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">aggregate_select</span><span class="p">:</span>
            <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">():</span>
                <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c"># When extra(select=...) or an annotation is involved, the extra</span>
            <span class="c"># cols are always at the start of the row, and we need to reorder</span>
            <span class="c"># the fields to match the order in self._fields.</span>
            <span class="n">extra_names</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">extra_select</span><span class="p">)</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">field_names</span>
            <span class="n">aggregate_names</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">aggregate_select</span><span class="p">)</span>

            <span class="n">names</span> <span class="o">=</span> <span class="n">extra_names</span> <span class="o">+</span> <span class="n">field_names</span> <span class="o">+</span> <span class="n">aggregate_names</span>

            <span class="c"># If a field list has been specified, use it. Otherwise, use the</span>
            <span class="c"># full list of fields, including extras and aggregates.</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">:</span>
                <span class="n">fields</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span> <span class="o">+</span> <span class="p">[</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">aggregate_names</span> <span class="k">if</span> <span class="n">f</span> <span class="ow">not</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fields</span><span class="p">]</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">fields</span> <span class="o">=</span> <span class="n">names</span>

            <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">():</span>
                <span class="n">data</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">names</span><span class="p">,</span> <span class="n">row</span><span class="p">))</span>
                <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">f</span><span class="p">]</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">clone</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">ValuesListQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">clone</span><span class="p">,</span> <span class="s">&quot;flat&quot;</span><span class="p">):</span>
            <span class="c"># Only assign flat if the clone didn&#39;t already get it from kwargs</span>
            <span class="n">clone</span><span class="o">.</span><span class="n">flat</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">flat</span>
        <span class="k">return</span> <span class="n">clone</span>


<span class="k">class</span> <span class="nc">DateQuerySet</span><span class="p">(</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">_setup_query</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Sets up any special features of the query attribute.</span>

<span class="sd">        Called by the _clone() method after initializing the rest of the</span>
<span class="sd">        instance.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_deferred_loading</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">sql</span><span class="o">.</span><span class="n">DateQuery</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_select</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_field_name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_kind</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_order</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">klass</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">c</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">DateQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_field_name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_field_name</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_kind</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_kind</span>
        <span class="k">if</span> <span class="n">setup</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s">&#39;_setup_query&#39;</span><span class="p">):</span>
            <span class="n">c</span><span class="o">.</span><span class="n">_setup_query</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">c</span>


<span class="k">class</span> <span class="nc">DateTimeQuerySet</span><span class="p">(</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_compiler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">)</span><span class="o">.</span><span class="n">results_iter</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">_setup_query</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Sets up any special features of the query attribute.</span>

<span class="sd">        Called by the _clone() method after initializing the rest of the</span>
<span class="sd">        instance.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clear_deferred_loading</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">(</span><span class="n">klass</span><span class="o">=</span><span class="n">sql</span><span class="o">.</span><span class="n">DateTimeQuery</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_tzinfo</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">select</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">add_select</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_field_name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_kind</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_order</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">klass</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">c</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">DateTimeQuerySet</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="bp">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_field_name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_field_name</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_kind</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_kind</span>
        <span class="n">c</span><span class="o">.</span><span class="n">_tzinfo</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_tzinfo</span>
        <span class="k">if</span> <span class="n">setup</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s">&#39;_setup_query&#39;</span><span class="p">):</span>
            <span class="n">c</span><span class="o">.</span><span class="n">_setup_query</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">c</span>


<span class="k">def</span> <span class="nf">get_klass_info</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="n">max_depth</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">cur_depth</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">requested</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
                   <span class="n">only_load</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">from_parent</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Helper function that recursively returns an information for a klass, to be</span>
<span class="sd">    used in get_cached_row.  It exists just to compute this information only</span>
<span class="sd">    once for entire queryset. Otherwise it would be computed for each row, which</span>
<span class="sd">    leads to poor performance on large querysets.</span>

<span class="sd">    Arguments:</span>
<span class="sd">     * klass - the class to retrieve (and instantiate)</span>
<span class="sd">     * max_depth - the maximum depth to which a select_related()</span>
<span class="sd">       relationship should be explored.</span>
<span class="sd">     * cur_depth - the current depth in the select_related() tree.</span>
<span class="sd">       Used in recursive calls to determine if we should dig deeper.</span>
<span class="sd">     * requested - A dictionary describing the select_related() tree</span>
<span class="sd">       that is to be retrieved. keys are field names; values are</span>
<span class="sd">       dictionaries describing the keys on that related object that</span>
<span class="sd">       are themselves to be select_related().</span>
<span class="sd">     * only_load - if the query has had only() or defer() applied,</span>
<span class="sd">       this is the list of field names that will be returned. If None,</span>
<span class="sd">       the full field list for `klass` can be assumed.</span>
<span class="sd">     * from_parent - the parent model used to get to this model</span>

<span class="sd">    Note that when travelling from parent to child, we will only load child</span>
<span class="sd">    fields which aren&#39;t in the parent.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">max_depth</span> <span class="ow">and</span> <span class="n">requested</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">cur_depth</span> <span class="o">&gt;</span> <span class="n">max_depth</span><span class="p">:</span>
        <span class="c"># We&#39;ve recursed deeply enough; stop now.</span>
        <span class="k">return</span> <span class="bp">None</span>

    <span class="k">if</span> <span class="n">only_load</span><span class="p">:</span>
        <span class="n">load_fields</span> <span class="o">=</span> <span class="n">only_load</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">klass</span><span class="p">)</span> <span class="ow">or</span> <span class="nb">set</span><span class="p">()</span>
        <span class="c"># When we create the object, we will also be creating populating</span>
        <span class="c"># all the parent classes, so traverse the parent classes looking</span>
        <span class="c"># for fields that must be included on load.</span>
        <span class="k">for</span> <span class="n">parent</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_parent_list</span><span class="p">():</span>
            <span class="n">fields</span> <span class="o">=</span> <span class="n">only_load</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">parent</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">fields</span><span class="p">:</span>
                <span class="n">load_fields</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">load_fields</span> <span class="o">=</span> <span class="bp">None</span>

    <span class="k">if</span> <span class="n">load_fields</span><span class="p">:</span>
        <span class="c"># Handle deferred fields.</span>
        <span class="n">skip</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
        <span class="n">init_list</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="c"># Build the list of fields that *haven&#39;t* been requested</span>
        <span class="k">for</span> <span class="n">field</span><span class="p">,</span> <span class="n">model</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_concrete_fields_with_model</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">from_parent</span> <span class="ow">and</span> <span class="n">model</span> <span class="ow">and</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">from_parent</span><span class="p">,</span> <span class="n">model</span><span class="p">):</span>
                <span class="c"># Avoid loading fields already loaded for parent model for</span>
                <span class="c"># child models.</span>
                <span class="k">continue</span>
            <span class="k">elif</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">load_fields</span><span class="p">:</span>
                <span class="n">skip</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">init_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
        <span class="c"># Retrieve all the requested fields</span>
        <span class="n">field_count</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">init_list</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">skip</span><span class="p">:</span>
            <span class="n">klass</span> <span class="o">=</span> <span class="n">deferred_class_factory</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="n">skip</span><span class="p">)</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="n">init_list</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c"># Load all fields on klass</span>

        <span class="n">field_count</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">)</span>
        <span class="c"># Check if we need to skip some parent fields.</span>
        <span class="k">if</span> <span class="n">from_parent</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">local_concrete_fields</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">):</span>
            <span class="c"># Only load those fields which haven&#39;t been already loaded into</span>
            <span class="c"># &#39;from_parent&#39;.</span>
            <span class="n">non_seen_models</span> <span class="o">=</span> <span class="p">[</span><span class="n">p</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_parent_list</span><span class="p">()</span>
                               <span class="k">if</span> <span class="ow">not</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">from_parent</span><span class="p">,</span> <span class="n">p</span><span class="p">)]</span>
            <span class="c"># Load local fields, too...</span>
            <span class="n">non_seen_models</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">klass</span><span class="p">)</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span><span class="o">.</span><span class="n">attname</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span>
                           <span class="k">if</span> <span class="n">f</span><span class="o">.</span><span class="n">model</span> <span class="ow">in</span> <span class="n">non_seen_models</span><span class="p">]</span>
            <span class="n">field_count</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">field_names</span><span class="p">)</span>
        <span class="c"># Try to avoid populating field_names variable for performance reasons.</span>
        <span class="c"># If field_names variable is set, we use **kwargs based model init</span>
        <span class="c"># which is slower than normal init.</span>
        <span class="k">if</span> <span class="n">field_count</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">concrete_fields</span><span class="p">):</span>
            <span class="n">field_names</span> <span class="o">=</span> <span class="p">()</span>

    <span class="n">restricted</span> <span class="o">=</span> <span class="n">requested</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span>

    <span class="n">related_fields</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">select_related_descend</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">restricted</span><span class="p">,</span> <span class="n">requested</span><span class="p">,</span> <span class="n">load_fields</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">restricted</span><span class="p">:</span>
                <span class="nb">next</span> <span class="o">=</span> <span class="n">requested</span><span class="p">[</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">]</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="nb">next</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="n">klass_info</span> <span class="o">=</span> <span class="n">get_klass_info</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">rel</span><span class="o">.</span><span class="n">to</span><span class="p">,</span> <span class="n">max_depth</span><span class="o">=</span><span class="n">max_depth</span><span class="p">,</span> <span class="n">cur_depth</span><span class="o">=</span><span class="n">cur_depth</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span>
                                        <span class="n">requested</span><span class="o">=</span><span class="nb">next</span><span class="p">,</span> <span class="n">only_load</span><span class="o">=</span><span class="n">only_load</span><span class="p">)</span>
            <span class="n">related_fields</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">f</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">))</span>

    <span class="n">reverse_related_fields</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">if</span> <span class="n">restricted</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">o</span> <span class="ow">in</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_all_related_objects</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">o</span><span class="o">.</span><span class="n">field</span><span class="o">.</span><span class="n">unique</span> <span class="ow">and</span> <span class="n">select_related_descend</span><span class="p">(</span><span class="n">o</span><span class="o">.</span><span class="n">field</span><span class="p">,</span> <span class="n">restricted</span><span class="p">,</span> <span class="n">requested</span><span class="p">,</span>
                                                         <span class="n">only_load</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">o</span><span class="o">.</span><span class="n">model</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">):</span>
                <span class="nb">next</span> <span class="o">=</span> <span class="n">requested</span><span class="p">[</span><span class="n">o</span><span class="o">.</span><span class="n">field</span><span class="o">.</span><span class="n">related_query_name</span><span class="p">()]</span>
                <span class="n">parent</span> <span class="o">=</span> <span class="n">klass</span> <span class="k">if</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">o</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">klass</span><span class="p">)</span> <span class="k">else</span> <span class="bp">None</span>
                <span class="n">klass_info</span> <span class="o">=</span> <span class="n">get_klass_info</span><span class="p">(</span><span class="n">o</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">max_depth</span><span class="o">=</span><span class="n">max_depth</span><span class="p">,</span> <span class="n">cur_depth</span><span class="o">=</span><span class="n">cur_depth</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span>
                                            <span class="n">requested</span><span class="o">=</span><span class="nb">next</span><span class="p">,</span> <span class="n">only_load</span><span class="o">=</span><span class="n">only_load</span><span class="p">,</span> <span class="n">from_parent</span><span class="o">=</span><span class="n">parent</span><span class="p">)</span>
                <span class="n">reverse_related_fields</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">o</span><span class="o">.</span><span class="n">field</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">))</span>
    <span class="k">if</span> <span class="n">field_names</span><span class="p">:</span>
        <span class="n">pk_idx</span> <span class="o">=</span> <span class="n">field_names</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">pk</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">pk_idx</span> <span class="o">=</span> <span class="n">klass</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">pk_index</span><span class="p">()</span>

    <span class="k">return</span> <span class="n">klass</span><span class="p">,</span> <span class="n">field_names</span><span class="p">,</span> <span class="n">field_count</span><span class="p">,</span> <span class="n">related_fields</span><span class="p">,</span> <span class="n">reverse_related_fields</span><span class="p">,</span> <span class="n">pk_idx</span>


<span class="k">def</span> <span class="nf">get_cached_row</span><span class="p">(</span><span class="n">row</span><span class="p">,</span> <span class="n">index_start</span><span class="p">,</span> <span class="n">using</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">,</span> <span class="n">offset</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
                   <span class="n">parent_data</span><span class="o">=</span><span class="p">()):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Helper function that recursively returns an object with the specified</span>
<span class="sd">    related attributes already populated.</span>

<span class="sd">    This method may be called recursively to populate deep select_related()</span>
<span class="sd">    clauses.</span>

<span class="sd">    Arguments:</span>
<span class="sd">         * row - the row of data returned by the database cursor</span>
<span class="sd">         * index_start - the index of the row at which data for this</span>
<span class="sd">           object is known to start</span>
<span class="sd">         * offset - the number of additional fields that are known to</span>
<span class="sd">           exist in row for `klass`. This usually means the number of</span>
<span class="sd">           annotated results on `klass`.</span>
<span class="sd">         * using - the database alias on which the query is being executed.</span>
<span class="sd">         * klass_info - result of the get_klass_info function</span>
<span class="sd">         * parent_data - parent model data in format (field, value). Used</span>
<span class="sd">           to populate the non-local fields of child models.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">klass_info</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="bp">None</span>
    <span class="n">klass</span><span class="p">,</span> <span class="n">field_names</span><span class="p">,</span> <span class="n">field_count</span><span class="p">,</span> <span class="n">related_fields</span><span class="p">,</span> <span class="n">reverse_related_fields</span><span class="p">,</span> <span class="n">pk_idx</span> <span class="o">=</span> <span class="n">klass_info</span>

    <span class="n">fields</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="n">index_start</span><span class="p">:</span><span class="n">index_start</span> <span class="o">+</span> <span class="n">field_count</span><span class="p">]</span>
    <span class="c"># If the pk column is None (or the equivalent &#39;&#39; in the case the</span>
    <span class="c"># connection interprets empty strings as nulls), then the related</span>
    <span class="c"># object must be non-existent - set the relation to None.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fields</span><span class="p">[</span><span class="n">pk_idx</span><span class="p">]</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span>
        <span class="p">(</span><span class="n">connections</span><span class="p">[</span><span class="n">using</span><span class="p">]</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">interprets_empty_strings_as_nulls</span> <span class="ow">and</span>
         <span class="n">fields</span><span class="p">[</span><span class="n">pk_idx</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;&#39;</span><span class="p">)):</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="k">elif</span> <span class="n">field_names</span><span class="p">:</span>
        <span class="n">fields</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">rel_field</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">parent_data</span><span class="p">:</span>
            <span class="n">field_names</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">rel_field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
            <span class="n">fields</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="n">klass</span><span class="p">(</span><span class="o">**</span><span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">field_names</span><span class="p">,</span> <span class="n">fields</span><span class="p">)))</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="n">klass</span><span class="p">(</span><span class="o">*</span><span class="n">fields</span><span class="p">)</span>
    <span class="c"># If an object was retrieved, set the database state.</span>
    <span class="k">if</span> <span class="n">obj</span><span class="p">:</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">db</span> <span class="o">=</span> <span class="n">using</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="bp">False</span>

    <span class="c"># Instantiate related fields</span>
    <span class="n">index_end</span> <span class="o">=</span> <span class="n">index_start</span> <span class="o">+</span> <span class="n">field_count</span> <span class="o">+</span> <span class="n">offset</span>
    <span class="c"># Iterate over each related object, populating any</span>
    <span class="c"># select_related() fields</span>
    <span class="k">for</span> <span class="n">f</span><span class="p">,</span> <span class="n">klass_info</span> <span class="ow">in</span> <span class="n">related_fields</span><span class="p">:</span>
        <span class="c"># Recursively retrieve the data for the related object</span>
        <span class="n">cached_row</span> <span class="o">=</span> <span class="n">get_cached_row</span><span class="p">(</span><span class="n">row</span><span class="p">,</span> <span class="n">index_end</span><span class="p">,</span> <span class="n">using</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">)</span>
        <span class="c"># If the recursive descent found an object, populate the</span>
        <span class="c"># descriptor caches relevant to the object</span>
        <span class="k">if</span> <span class="n">cached_row</span><span class="p">:</span>
            <span class="n">rel_obj</span><span class="p">,</span> <span class="n">index_end</span> <span class="o">=</span> <span class="n">cached_row</span>
            <span class="k">if</span> <span class="n">obj</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="c"># If the base object exists, populate the</span>
                <span class="c"># descriptor cache</span>
                <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">(),</span> <span class="n">rel_obj</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">f</span><span class="o">.</span><span class="n">unique</span> <span class="ow">and</span> <span class="n">rel_obj</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="c"># If the field is unique, populate the</span>
                <span class="c"># reverse descriptor cache on the related object</span>
                <span class="nb">setattr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">related</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">(),</span> <span class="n">obj</span><span class="p">)</span>

    <span class="c"># Now do the same, but for reverse related objects.</span>
    <span class="c"># Only handle the restricted case - i.e., don&#39;t do a depth</span>
    <span class="c"># descent into reverse relations unless explicitly requested</span>
    <span class="k">for</span> <span class="n">f</span><span class="p">,</span> <span class="n">klass_info</span> <span class="ow">in</span> <span class="n">reverse_related_fields</span><span class="p">:</span>
        <span class="c"># Transfer data from this object to childs.</span>
        <span class="n">parent_data</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">rel_field</span><span class="p">,</span> <span class="n">rel_model</span> <span class="ow">in</span> <span class="n">klass_info</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">get_fields_with_model</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">rel_model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">rel_model</span><span class="p">):</span>
                <span class="n">parent_data</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">rel_field</span><span class="p">,</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">attname</span><span class="p">)))</span>
        <span class="c"># Recursively retrieve the data for the related object</span>
        <span class="n">cached_row</span> <span class="o">=</span> <span class="n">get_cached_row</span><span class="p">(</span><span class="n">row</span><span class="p">,</span> <span class="n">index_end</span><span class="p">,</span> <span class="n">using</span><span class="p">,</span> <span class="n">klass_info</span><span class="p">,</span>
                                   <span class="n">parent_data</span><span class="o">=</span><span class="n">parent_data</span><span class="p">)</span>
        <span class="c"># If the recursive descent found an object, populate the</span>
        <span class="c"># descriptor caches relevant to the object</span>
        <span class="k">if</span> <span class="n">cached_row</span><span class="p">:</span>
            <span class="n">rel_obj</span><span class="p">,</span> <span class="n">index_end</span> <span class="o">=</span> <span class="n">cached_row</span>
            <span class="k">if</span> <span class="n">obj</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="c"># populate the reverse descriptor cache</span>
                <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">related</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">(),</span> <span class="n">rel_obj</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">rel_obj</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="c"># If the related object exists, populate</span>
                <span class="c"># the descriptor cache.</span>
                <span class="nb">setattr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">(),</span> <span class="n">obj</span><span class="p">)</span>
                <span class="c"># Populate related object caches using parent data.</span>
                <span class="k">for</span> <span class="n">rel_field</span><span class="p">,</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">parent_data</span><span class="p">:</span>
                    <span class="k">if</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">rel</span><span class="p">:</span>
                        <span class="nb">setattr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">,</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">attname</span><span class="p">,</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">attname</span><span class="p">))</span>
                        <span class="k">try</span><span class="p">:</span>
                            <span class="n">cached_obj</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">())</span>
                            <span class="nb">setattr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">,</span> <span class="n">rel_field</span><span class="o">.</span><span class="n">get_cache_name</span><span class="p">(),</span> <span class="n">cached_obj</span><span class="p">)</span>
                        <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
                            <span class="c"># Related object hasn&#39;t been cached yet</span>
                            <span class="k">pass</span>
    <span class="k">return</span> <span class="n">obj</span><span class="p">,</span> <span class="n">index_end</span>


<span class="k">class</span> <span class="nc">RawQuerySet</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Provides an iterator which converts the results of raw SQL queries into</span>
<span class="sd">    annotated model instances.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">raw_query</span><span class="p">,</span> <span class="n">model</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">query</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
            <span class="n">translations</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">hints</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">raw_query</span> <span class="o">=</span> <span class="n">raw_query</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">model</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_db</span> <span class="o">=</span> <span class="n">using</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_hints</span> <span class="o">=</span> <span class="n">hints</span> <span class="ow">or</span> <span class="p">{}</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="n">query</span> <span class="ow">or</span> <span class="n">sql</span><span class="o">.</span><span class="n">RawQuery</span><span class="p">(</span><span class="n">sql</span><span class="o">=</span><span class="n">raw_query</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="n">params</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">params</span> <span class="o">=</span> <span class="n">params</span> <span class="ow">or</span> <span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">translations</span> <span class="o">=</span> <span class="n">translations</span> <span class="ow">or</span> <span class="p">{}</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Mapping of attrnames to row column positions. Used for constructing</span>
        <span class="c"># the model using kwargs, needed when not all model&#39;s fields are present</span>
        <span class="c"># in the query.</span>
        <span class="n">model_init_field_names</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="c"># A list of tuples of (column name, column position). Used for</span>
        <span class="c"># annotation fields.</span>
        <span class="n">annotation_fields</span> <span class="o">=</span> <span class="p">[]</span>

        <span class="c"># Cache some things for performance reasons outside the loop.</span>
        <span class="n">db</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>
        <span class="n">compiler</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="n">db</span><span class="p">]</span><span class="o">.</span><span class="n">ops</span><span class="o">.</span><span class="n">compiler</span><span class="p">(</span><span class="s">&#39;SQLCompiler&#39;</span><span class="p">)(</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="p">,</span> <span class="n">connections</span><span class="p">[</span><span class="n">db</span><span class="p">],</span> <span class="n">db</span>
        <span class="p">)</span>
        <span class="n">need_resolv_columns</span> <span class="o">=</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">compiler</span><span class="p">,</span> <span class="s">&#39;resolve_columns&#39;</span><span class="p">)</span>

        <span class="n">query</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="p">)</span>

        <span class="k">try</span><span class="p">:</span>
            <span class="c"># Find out which columns are model&#39;s fields, and which ones should be</span>
            <span class="c"># annotated to the model.</span>
            <span class="k">for</span> <span class="n">pos</span><span class="p">,</span> <span class="n">column</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">):</span>
                <span class="k">if</span> <span class="n">column</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_fields</span><span class="p">:</span>
                    <span class="n">model_init_field_names</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">model_fields</span><span class="p">[</span><span class="n">column</span><span class="p">]</span><span class="o">.</span><span class="n">attname</span><span class="p">]</span> <span class="o">=</span> <span class="n">pos</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">annotation_fields</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">column</span><span class="p">,</span> <span class="n">pos</span><span class="p">))</span>

            <span class="c"># Find out which model&#39;s fields are not present in the query.</span>
            <span class="n">skip</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
            <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">field</span><span class="o">.</span><span class="n">attname</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">model_init_field_names</span><span class="p">:</span>
                    <span class="n">skip</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">skip</span><span class="p">:</span>
                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">pk</span><span class="o">.</span><span class="n">attname</span> <span class="ow">in</span> <span class="n">skip</span><span class="p">:</span>
                    <span class="k">raise</span> <span class="n">InvalidQuery</span><span class="p">(</span><span class="s">&#39;Raw query must include the primary key&#39;</span><span class="p">)</span>
                <span class="n">model_cls</span> <span class="o">=</span> <span class="n">deferred_class_factory</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">skip</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">model_cls</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span>
                <span class="c"># All model&#39;s fields are present in the query. So, it is possible</span>
                <span class="c"># to use *args based model instantiation. For each field of the model,</span>
                <span class="c"># record the query column position matching that field.</span>
                <span class="n">model_init_field_pos</span> <span class="o">=</span> <span class="p">[]</span>
                <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">:</span>
                    <span class="n">model_init_field_pos</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">model_init_field_names</span><span class="p">[</span><span class="n">field</span><span class="o">.</span><span class="n">attname</span><span class="p">])</span>
            <span class="k">if</span> <span class="n">need_resolv_columns</span><span class="p">:</span>
                <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">model_fields</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">]</span>
            <span class="c"># Begin looping through the query values.</span>
            <span class="k">for</span> <span class="n">values</span> <span class="ow">in</span> <span class="n">query</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">need_resolv_columns</span><span class="p">:</span>
                    <span class="n">values</span> <span class="o">=</span> <span class="n">compiler</span><span class="o">.</span><span class="n">resolve_columns</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="n">fields</span><span class="p">)</span>
                <span class="c"># Associate fields to values</span>
                <span class="k">if</span> <span class="n">skip</span><span class="p">:</span>
                    <span class="n">model_init_kwargs</span> <span class="o">=</span> <span class="p">{}</span>
                    <span class="k">for</span> <span class="n">attname</span><span class="p">,</span> <span class="n">pos</span> <span class="ow">in</span> <span class="n">six</span><span class="o">.</span><span class="n">iteritems</span><span class="p">(</span><span class="n">model_init_field_names</span><span class="p">):</span>
                        <span class="n">model_init_kwargs</span><span class="p">[</span><span class="n">attname</span><span class="p">]</span> <span class="o">=</span> <span class="n">values</span><span class="p">[</span><span class="n">pos</span><span class="p">]</span>
                    <span class="n">instance</span> <span class="o">=</span> <span class="n">model_cls</span><span class="p">(</span><span class="o">**</span><span class="n">model_init_kwargs</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">model_init_args</span> <span class="o">=</span> <span class="p">[</span><span class="n">values</span><span class="p">[</span><span class="n">pos</span><span class="p">]</span> <span class="k">for</span> <span class="n">pos</span> <span class="ow">in</span> <span class="n">model_init_field_pos</span><span class="p">]</span>
                    <span class="n">instance</span> <span class="o">=</span> <span class="n">model_cls</span><span class="p">(</span><span class="o">*</span><span class="n">model_init_args</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">annotation_fields</span><span class="p">:</span>
                    <span class="k">for</span> <span class="n">column</span><span class="p">,</span> <span class="n">pos</span> <span class="ow">in</span> <span class="n">annotation_fields</span><span class="p">:</span>
                        <span class="nb">setattr</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">values</span><span class="p">[</span><span class="n">pos</span><span class="p">])</span>

                <span class="n">instance</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">db</span> <span class="o">=</span> <span class="n">db</span>
                <span class="n">instance</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="bp">False</span>

                <span class="k">yield</span> <span class="n">instance</span>
        <span class="k">finally</span><span class="p">:</span>
            <span class="c"># Done iterating the Query. If it has its own cursor, close it.</span>
            <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="p">,</span> <span class="s">&#39;cursor&#39;</span><span class="p">)</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">cursor</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">cursor</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">text</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">raw_query</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">params</span><span class="p">:</span>
            <span class="n">text</span> <span class="o">=</span> <span class="n">text</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">params</span> <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">params</span><span class="p">,</span> <span class="s">&#39;keys&#39;</span><span class="p">)</span> <span class="k">else</span> <span class="nb">tuple</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">params</span><span class="p">))</span>
        <span class="k">return</span> <span class="s">&quot;&lt;RawQuerySet: </span><span class="si">%r</span><span class="s">&gt;&quot;</span> <span class="o">%</span> <span class="n">text</span>

    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="p">)[</span><span class="n">k</span><span class="p">]</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">db</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Return the database that will be used if this query is executed now&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_db</span> <span class="ow">or</span> <span class="n">router</span><span class="o">.</span><span class="n">db_for_read</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">_hints</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">using</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">alias</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Selects which database this Raw QuerySet should execute its query against.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="n">RawQuerySet</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">raw_query</span><span class="p">,</span> <span class="n">model</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span>
                <span class="n">query</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">clone</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="n">alias</span><span class="p">),</span>
                <span class="n">params</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">params</span><span class="p">,</span> <span class="n">translations</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">translations</span><span class="p">,</span>
                <span class="n">using</span><span class="o">=</span><span class="n">alias</span><span class="p">)</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">columns</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        A list of model field names in the order they&#39;ll appear in the</span>
<span class="sd">        query results.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&#39;_columns&#39;</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_columns</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get_columns</span><span class="p">()</span>

            <span class="c"># Adjust any column names which don&#39;t match field names</span>
            <span class="k">for</span> <span class="p">(</span><span class="n">query_name</span><span class="p">,</span> <span class="n">model_name</span><span class="p">)</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">translations</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
                <span class="k">try</span><span class="p">:</span>
                    <span class="n">index</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_columns</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">query_name</span><span class="p">)</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_columns</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="o">=</span> <span class="n">model_name</span>
                <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
                    <span class="c"># Ignore translations for non-existent column names</span>
                    <span class="k">pass</span>

        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_columns</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">model_fields</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        A dict mapping column names to model field names.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&#39;_model_fields&#39;</span><span class="p">):</span>
            <span class="n">converter</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">db</span><span class="p">]</span><span class="o">.</span><span class="n">introspection</span><span class="o">.</span><span class="n">table_name_converter</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_model_fields</span> <span class="o">=</span> <span class="p">{}</span>
            <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">fields</span><span class="p">:</span>
                <span class="n">name</span><span class="p">,</span> <span class="n">column</span> <span class="o">=</span> <span class="n">field</span><span class="o">.</span><span class="n">get_attname_column</span><span class="p">()</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_model_fields</span><span class="p">[</span><span class="n">converter</span><span class="p">(</span><span class="n">column</span><span class="p">)]</span> <span class="o">=</span> <span class="n">field</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_model_fields</span>


<span class="k">class</span> <span class="nc">Prefetch</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">lookup</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="c"># `prefetch_through` is the path we traverse to perform the prefetch.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_through</span> <span class="o">=</span> <span class="n">lookup</span>
        <span class="c"># `prefetch_to` is the path to the attribute that stores the result.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span> <span class="o">=</span> <span class="n">lookup</span>
        <span class="k">if</span> <span class="n">to_attr</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span> <span class="o">=</span> <span class="n">LOOKUP_SEP</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">lookup</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">LOOKUP_SEP</span><span class="p">)[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="n">to_attr</span><span class="p">])</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">queryset</span> <span class="o">=</span> <span class="n">queryset</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">to_attr</span> <span class="o">=</span> <span class="n">to_attr</span>

    <span class="k">def</span> <span class="nf">add_prefix</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">prefix</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_through</span> <span class="o">=</span> <span class="n">LOOKUP_SEP</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">prefix</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_through</span><span class="p">])</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span> <span class="o">=</span> <span class="n">LOOKUP_SEP</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">prefix</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span><span class="p">])</span>

    <span class="k">def</span> <span class="nf">get_current_prefetch_through</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">LOOKUP_SEP</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">prefetch_through</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">LOOKUP_SEP</span><span class="p">)[:</span><span class="n">level</span> <span class="o">+</span> <span class="mi">1</span><span class="p">])</span>

    <span class="k">def</span> <span class="nf">get_current_prefetch_to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">LOOKUP_SEP</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">LOOKUP_SEP</span><span class="p">)[:</span><span class="n">level</span> <span class="o">+</span> <span class="mi">1</span><span class="p">])</span>

    <span class="k">def</span> <span class="nf">get_current_to_attr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
        <span class="n">parts</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">LOOKUP_SEP</span><span class="p">)</span>
        <span class="n">to_attr</span> <span class="o">=</span> <span class="n">parts</span><span class="p">[</span><span class="n">level</span><span class="p">]</span>
        <span class="n">as_attr</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">to_attr</span> <span class="ow">and</span> <span class="n">level</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">parts</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="k">return</span> <span class="n">to_attr</span><span class="p">,</span> <span class="n">as_attr</span>

    <span class="k">def</span> <span class="nf">get_current_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_current_prefetch_to</span><span class="p">(</span><span class="n">level</span><span class="p">)</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">queryset</span>
        <span class="k">return</span> <span class="bp">None</span>

    <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">prefetch_to</span>
        <span class="k">return</span> <span class="bp">False</span>

    <span class="k">def</span> <span class="nf">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">hash</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="p">)</span> <span class="o">^</span> <span class="nb">hash</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">prefetch_to</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">normalize_prefetch_lookups</span><span class="p">(</span><span class="n">lookups</span><span class="p">,</span> <span class="n">prefix</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Helper function that normalize lookups into Prefetch objects.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">ret</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">lookup</span> <span class="ow">in</span> <span class="n">lookups</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">lookup</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">):</span>
            <span class="n">lookup</span> <span class="o">=</span> <span class="n">Prefetch</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">prefix</span><span class="p">:</span>
            <span class="n">lookup</span><span class="o">.</span><span class="n">add_prefix</span><span class="p">(</span><span class="n">prefix</span><span class="p">)</span>
        <span class="n">ret</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">lookup</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ret</span>


<span class="k">def</span> <span class="nf">prefetch_related_objects</span><span class="p">(</span><span class="n">result_cache</span><span class="p">,</span> <span class="n">related_lookups</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Helper function for prefetch_related functionality</span>

<span class="sd">    Populates prefetched objects caches for a list of results</span>
<span class="sd">    from a QuerySet</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">result_cache</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">return</span>  <span class="c"># nothing to do</span>

    <span class="n">related_lookups</span> <span class="o">=</span> <span class="n">normalize_prefetch_lookups</span><span class="p">(</span><span class="n">related_lookups</span><span class="p">)</span>

    <span class="c"># We need to be able to dynamically add to the list of prefetch_related</span>
    <span class="c"># lookups that we look up (see below).  So we need some book keeping to</span>
    <span class="c"># ensure we don&#39;t do duplicate work.</span>
    <span class="n">done_queries</span> <span class="o">=</span> <span class="p">{}</span>    <span class="c"># dictionary of things like &#39;foo__bar&#39;: [results]</span>

    <span class="n">auto_lookups</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>  <span class="c"># we add to this as we go through.</span>
    <span class="n">followed_descriptors</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>  <span class="c"># recursion protection</span>

    <span class="n">all_lookups</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">related_lookups</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">all_lookups</span><span class="p">:</span>
        <span class="n">lookup</span> <span class="o">=</span> <span class="n">all_lookups</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">lookup</span><span class="o">.</span><span class="n">prefetch_to</span> <span class="ow">in</span> <span class="n">done_queries</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">lookup</span><span class="o">.</span><span class="n">queryset</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;&#39;</span><span class="si">%s</span><span class="s">&#39; lookup was already seen with a different queryset. &quot;</span>
                                 <span class="s">&quot;You may need to adjust the ordering of your lookups.&quot;</span> <span class="o">%</span> <span class="n">lookup</span><span class="o">.</span><span class="n">prefetch_to</span><span class="p">)</span>

            <span class="k">continue</span>

        <span class="c"># Top level, the list of objects to decorate is the result cache</span>
        <span class="c"># from the primary QuerySet. It won&#39;t be for deeper levels.</span>
        <span class="n">obj_list</span> <span class="o">=</span> <span class="n">result_cache</span>

        <span class="n">through_attrs</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">prefetch_through</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">LOOKUP_SEP</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">level</span><span class="p">,</span> <span class="n">through_attr</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">through_attrs</span><span class="p">):</span>
            <span class="c"># Prepare main instances</span>
            <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">obj_list</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="k">break</span>

            <span class="n">prefetch_to</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_current_prefetch_to</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">prefetch_to</span> <span class="ow">in</span> <span class="n">done_queries</span><span class="p">:</span>
                <span class="c"># Skip any prefetching, and any object preparation</span>
                <span class="n">obj_list</span> <span class="o">=</span> <span class="n">done_queries</span><span class="p">[</span><span class="n">prefetch_to</span><span class="p">]</span>
                <span class="k">continue</span>

            <span class="c"># Prepare objects:</span>
            <span class="n">good_objects</span> <span class="o">=</span> <span class="bp">True</span>
            <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">obj_list</span><span class="p">:</span>
                <span class="c"># Since prefetching can re-use instances, it is possible to have</span>
                <span class="c"># the same instance multiple times in obj_list, so obj might</span>
                <span class="c"># already be prepared.</span>
                <span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s">&#39;_prefetched_objects_cache&#39;</span><span class="p">):</span>
                    <span class="k">try</span><span class="p">:</span>
                        <span class="n">obj</span><span class="o">.</span><span class="n">_prefetched_objects_cache</span> <span class="o">=</span> <span class="p">{}</span>
                    <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
                        <span class="c"># Must be in a QuerySet subclass that is not returning</span>
                        <span class="c"># Model instances, either in Django or 3rd</span>
                        <span class="c"># party. prefetch_related() doesn&#39;t make sense, so quit</span>
                        <span class="c"># now.</span>
                        <span class="n">good_objects</span> <span class="o">=</span> <span class="bp">False</span>
                        <span class="k">break</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">good_objects</span><span class="p">:</span>
                <span class="k">break</span>

            <span class="c"># Descend down tree</span>

            <span class="c"># We assume that objects retrieved are homogeneous (which is the premise</span>
            <span class="c"># of prefetch_related), so what applies to first object applies to all.</span>
            <span class="n">first_obj</span> <span class="o">=</span> <span class="n">obj_list</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
            <span class="n">prefetcher</span><span class="p">,</span> <span class="n">descriptor</span><span class="p">,</span> <span class="n">attr_found</span><span class="p">,</span> <span class="n">is_fetched</span> <span class="o">=</span> <span class="n">get_prefetcher</span><span class="p">(</span><span class="n">first_obj</span><span class="p">,</span> <span class="n">through_attr</span><span class="p">)</span>

            <span class="k">if</span> <span class="ow">not</span> <span class="n">attr_found</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">AttributeError</span><span class="p">(</span><span class="s">&quot;Cannot find &#39;</span><span class="si">%s</span><span class="s">&#39; on </span><span class="si">%s</span><span class="s"> object, &#39;</span><span class="si">%s</span><span class="s">&#39; is an invalid &quot;</span>
                                     <span class="s">&quot;parameter to prefetch_related()&quot;</span> <span class="o">%</span>
                                     <span class="p">(</span><span class="n">through_attr</span><span class="p">,</span> <span class="n">first_obj</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">lookup</span><span class="o">.</span><span class="n">prefetch_through</span><span class="p">))</span>

            <span class="k">if</span> <span class="n">level</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">through_attrs</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span> <span class="ow">and</span> <span class="n">prefetcher</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
                <span class="c"># Last one, this *must* resolve to something that supports</span>
                <span class="c"># prefetching, otherwise there is no point adding it and the</span>
                <span class="c"># developer asking for it has made a mistake.</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">&quot;&#39;</span><span class="si">%s</span><span class="s">&#39; does not resolve to an item that supports &quot;</span>
                                 <span class="s">&quot;prefetching - this is an invalid parameter to &quot;</span>
                                 <span class="s">&quot;prefetch_related().&quot;</span> <span class="o">%</span> <span class="n">lookup</span><span class="o">.</span><span class="n">prefetch_through</span><span class="p">)</span>

            <span class="k">if</span> <span class="n">prefetcher</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">is_fetched</span><span class="p">:</span>
                <span class="n">obj_list</span><span class="p">,</span> <span class="n">additional_lookups</span> <span class="o">=</span> <span class="n">prefetch_one_level</span><span class="p">(</span><span class="n">obj_list</span><span class="p">,</span> <span class="n">prefetcher</span><span class="p">,</span> <span class="n">lookup</span><span class="p">,</span> <span class="n">level</span><span class="p">)</span>
                <span class="c"># We need to ensure we don&#39;t keep adding lookups from the</span>
                <span class="c"># same relationships to stop infinite recursion. So, if we</span>
                <span class="c"># are already on an automatically added lookup, don&#39;t add</span>
                <span class="c"># the new lookups from relationships we&#39;ve seen already.</span>
                <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">lookup</span> <span class="ow">in</span> <span class="n">auto_lookups</span> <span class="ow">and</span> <span class="n">descriptor</span> <span class="ow">in</span> <span class="n">followed_descriptors</span><span class="p">):</span>
                    <span class="n">done_queries</span><span class="p">[</span><span class="n">prefetch_to</span><span class="p">]</span> <span class="o">=</span> <span class="n">obj_list</span>
                    <span class="n">new_lookups</span> <span class="o">=</span> <span class="n">normalize_prefetch_lookups</span><span class="p">(</span><span class="n">additional_lookups</span><span class="p">,</span> <span class="n">prefetch_to</span><span class="p">)</span>
                    <span class="n">auto_lookups</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">new_lookups</span><span class="p">)</span>
                    <span class="n">all_lookups</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="n">new_lookups</span><span class="p">)</span>
                <span class="n">followed_descriptors</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">descriptor</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c"># Either a singly related object that has already been fetched</span>
                <span class="c"># (e.g. via select_related), or hopefully some other property</span>
                <span class="c"># that doesn&#39;t support prefetching but needs to be traversed.</span>

                <span class="c"># We replace the current list of parent objects with the list</span>
                <span class="c"># of related objects, filtering out empty or missing values so</span>
                <span class="c"># that we can continue with nullable or reverse relations.</span>
                <span class="n">new_obj_list</span> <span class="o">=</span> <span class="p">[]</span>
                <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">obj_list</span><span class="p">:</span>
                    <span class="k">try</span><span class="p">:</span>
                        <span class="n">new_obj</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">through_attr</span><span class="p">)</span>
                    <span class="k">except</span> <span class="n">exceptions</span><span class="o">.</span><span class="n">ObjectDoesNotExist</span><span class="p">:</span>
                        <span class="k">continue</span>
                    <span class="k">if</span> <span class="n">new_obj</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
                        <span class="k">continue</span>
                    <span class="c"># We special-case `list` rather than something more generic</span>
                    <span class="c"># like `Iterable` because we don&#39;t want to accidentally match</span>
                    <span class="c"># user models that define __iter__.</span>
                    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">new_obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span>
                        <span class="n">new_obj_list</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">new_obj</span><span class="p">)</span>
                    <span class="k">else</span><span class="p">:</span>
                        <span class="n">new_obj_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">new_obj</span><span class="p">)</span>
                <span class="n">obj_list</span> <span class="o">=</span> <span class="n">new_obj_list</span>


<span class="k">def</span> <span class="nf">get_prefetcher</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">attr</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    For the attribute &#39;attr&#39; on the given instance, finds</span>
<span class="sd">    an object that has a get_prefetch_queryset().</span>
<span class="sd">    Returns a 4 tuple containing:</span>
<span class="sd">    (the object with get_prefetch_queryset (or None),</span>
<span class="sd">     the descriptor object representing this relationship (or None),</span>
<span class="sd">     a boolean that is False if the attribute was not found at all,</span>
<span class="sd">     a boolean that is True if the attribute has already been fetched)</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">prefetcher</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="n">is_fetched</span> <span class="o">=</span> <span class="bp">False</span>

    <span class="c"># For singly related objects, we have to avoid getting the attribute</span>
    <span class="c"># from the object, as this will trigger the query. So we first try</span>
    <span class="c"># on the class, in order to get the descriptor object.</span>
    <span class="n">rel_obj_descriptor</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">instance</span><span class="o">.</span><span class="n">__class__</span><span class="p">,</span> <span class="n">attr</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">rel_obj_descriptor</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">attr_found</span> <span class="o">=</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">attr</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">attr_found</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">if</span> <span class="n">rel_obj_descriptor</span><span class="p">:</span>
            <span class="c"># singly related object, descriptor object has the</span>
            <span class="c"># get_prefetch_queryset() method.</span>
            <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">rel_obj_descriptor</span><span class="p">,</span> <span class="s">&#39;get_prefetch_queryset&#39;</span><span class="p">):</span>
                <span class="n">prefetcher</span> <span class="o">=</span> <span class="n">rel_obj_descriptor</span>
                <span class="k">if</span> <span class="n">rel_obj_descriptor</span><span class="o">.</span><span class="n">is_cached</span><span class="p">(</span><span class="n">instance</span><span class="p">):</span>
                    <span class="n">is_fetched</span> <span class="o">=</span> <span class="bp">True</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c"># descriptor doesn&#39;t support prefetching, so we go ahead and get</span>
                <span class="c"># the attribute on the instance rather than the class to</span>
                <span class="c"># support many related managers</span>
                <span class="n">rel_obj</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">attr</span><span class="p">)</span>
                <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">,</span> <span class="s">&#39;get_prefetch_queryset&#39;</span><span class="p">):</span>
                    <span class="n">prefetcher</span> <span class="o">=</span> <span class="n">rel_obj</span>
    <span class="k">return</span> <span class="n">prefetcher</span><span class="p">,</span> <span class="n">rel_obj_descriptor</span><span class="p">,</span> <span class="n">attr_found</span><span class="p">,</span> <span class="n">is_fetched</span>


<span class="k">def</span> <span class="nf">prefetch_one_level</span><span class="p">(</span><span class="n">instances</span><span class="p">,</span> <span class="n">prefetcher</span><span class="p">,</span> <span class="n">lookup</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Helper function for prefetch_related_objects</span>

<span class="sd">    Runs prefetches on all instances using the prefetcher object,</span>
<span class="sd">    assigning results to relevant caches in instance.</span>

<span class="sd">    The prefetched objects are returned, along with any additional</span>
<span class="sd">    prefetches that must be done due to prefetch_related lookups</span>
<span class="sd">    found from default managers.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c"># prefetcher must have a method get_prefetch_queryset() which takes a list</span>
    <span class="c"># of instances, and returns a tuple:</span>

    <span class="c"># (queryset of instances of self.model that are related to passed in instances,</span>
    <span class="c">#  callable that gets value to be matched for returned instances,</span>
    <span class="c">#  callable that gets value to be matched for passed in instances,</span>
    <span class="c">#  boolean that is True for singly related objects,</span>
    <span class="c">#  cache name to assign to).</span>

    <span class="c"># The &#39;values to be matched&#39; must be hashable as they will be used</span>
    <span class="c"># in a dictionary.</span>

    <span class="n">rel_qs</span><span class="p">,</span> <span class="n">rel_obj_attr</span><span class="p">,</span> <span class="n">instance_attr</span><span class="p">,</span> <span class="n">single</span><span class="p">,</span> <span class="n">cache_name</span> <span class="o">=</span> <span class="p">(</span>
        <span class="n">prefetcher</span><span class="o">.</span><span class="n">get_prefetch_queryset</span><span class="p">(</span><span class="n">instances</span><span class="p">,</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_current_queryset</span><span class="p">(</span><span class="n">level</span><span class="p">)))</span>
    <span class="c"># We have to handle the possibility that the QuerySet we just got back</span>
    <span class="c"># contains some prefetch_related lookups. We don&#39;t want to trigger the</span>
    <span class="c"># prefetch_related functionality by evaluating the query. Rather, we need</span>
    <span class="c"># to merge in the prefetch_related lookups.</span>
    <span class="n">additional_lookups</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">rel_qs</span><span class="p">,</span> <span class="s">&#39;_prefetch_related_lookups&#39;</span><span class="p">,</span> <span class="p">[])</span>
    <span class="k">if</span> <span class="n">additional_lookups</span><span class="p">:</span>
        <span class="c"># Don&#39;t need to clone because the manager should have given us a fresh</span>
        <span class="c"># instance, so we access an internal instead of using public interface</span>
        <span class="c"># for performance reasons.</span>
        <span class="n">rel_qs</span><span class="o">.</span><span class="n">_prefetch_related_lookups</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="n">all_related_objects</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">rel_qs</span><span class="p">)</span>

    <span class="n">rel_obj_cache</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">for</span> <span class="n">rel_obj</span> <span class="ow">in</span> <span class="n">all_related_objects</span><span class="p">:</span>
        <span class="n">rel_attr_val</span> <span class="o">=</span> <span class="n">rel_obj_attr</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">)</span>
        <span class="n">rel_obj_cache</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">rel_attr_val</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">rel_obj</span><span class="p">)</span>

    <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">instances</span><span class="p">:</span>
        <span class="n">instance_attr_val</span> <span class="o">=</span> <span class="n">instance_attr</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="n">vals</span> <span class="o">=</span> <span class="n">rel_obj_cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">instance_attr_val</span><span class="p">,</span> <span class="p">[])</span>
        <span class="n">to_attr</span><span class="p">,</span> <span class="n">as_attr</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_current_to_attr</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">single</span><span class="p">:</span>
            <span class="n">val</span> <span class="o">=</span> <span class="n">vals</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">if</span> <span class="n">vals</span> <span class="k">else</span> <span class="bp">None</span>
            <span class="n">to_attr</span> <span class="o">=</span> <span class="n">to_attr</span> <span class="k">if</span> <span class="n">as_attr</span> <span class="k">else</span> <span class="n">cache_name</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">to_attr</span><span class="p">,</span> <span class="n">val</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">as_attr</span><span class="p">:</span>
                <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">to_attr</span><span class="p">,</span> <span class="n">vals</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c"># Cache in the QuerySet.all().</span>
                <span class="n">qs</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">to_attr</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
                <span class="n">qs</span><span class="o">.</span><span class="n">_result_cache</span> <span class="o">=</span> <span class="n">vals</span>
                <span class="c"># We don&#39;t want the individual qs doing prefetch_related now,</span>
                <span class="c"># since we have merged this into the current work.</span>
                <span class="n">qs</span><span class="o">.</span><span class="n">_prefetch_done</span> <span class="o">=</span> <span class="bp">True</span>
                <span class="n">obj</span><span class="o">.</span><span class="n">_prefetched_objects_cache</span><span class="p">[</span><span class="n">cache_name</span><span class="p">]</span> <span class="o">=</span> <span class="n">qs</span>
    <span class="k">return</span> <span class="n">all_related_objects</span><span class="p">,</span> <span class="n">additional_lookups</span>
</pre></div>

          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3>Browse</h3>
  <ul>
    
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../../../index.html">Module code</a>
        
          <ul><li><a href="../../../django.html">django</a>
        
          <ul><li><a href="../../db.html">django.db</a>
        
          <ul><li><a href="../models.html">django.db.models</a>
        
        <ul><li>django.db.models.query</li></ul>
        </li></ul></li></ul></li></ul></li></ul>
      </li>
  </ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    <a href="../../../index.html" title="Module code" accesskey="U">up</a></div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>